thekeemo thekeemo - 1 month ago 17
jQuery Question

Filter a multi dimensional JS array using a keyword

I have an array that looks like this:

[['place', '1', '-2'],['place2', '1', '-2'],['place3', '1', '-3']]


I want to filter it using a keyword from onClick so it looks like this:

[['place', '1', '-2'],['place2', '1', '-2']]


If my filter is for example -2.

The code i'm using now is (where object is the variable being filtered):

return $.map(object, function (item, key) {
if (item[0] === value) {
return item;
}
});


And then I call it using:

var markers = results(filter);


But the result I get is blank.

Hopefully I am making sense if not I am very sorry please let me know and I can try to clarify.

Answer

You could use Array#filter for it and return the filtered items.

var data = [['place', '1', '-2'], ['place2', '1', '-2'], ['place3', '1', '-3']],
    filtered = data.filter(function (a) {
        return a[2] === '-2';
    });

console.log(filtered);

Search for any item with the given string

var data = [['place', '1', '-2'], ['place2', '1', '-2'], ['place3', '1', '-3']],
    filtered = data.filter(function (a) {
        return a.some(function (b) {
            return b === '-2';
        });
    });

console.log(filtered);

ES6, Search for any item with the given string

var data = [['place', '1', '-2'], ['place2', '1', '-2'], ['place3', '1', '-3']],
    filtered = data.filter(a => a.some(b => b === '-2'));

console.log(filtered);