Franck
Franck

Reputation: 2499

Filter a multidimensional array by another array in javascript

I'm trying to filter an array, from another array :

I have the first array :

var json = [["ID1", "Person1", "10"], ["ID2", "Person2", "20.0"], ["ID3", "Person3", "50.0"], ["ID4", "Person4", "40.0"]];

My filter array : (which is not ordered);

var filter = ["ID4", "ID1"]; 

And the result I would like to have :

var json = [["ID1", "Person1", "10"], ["ID4", "Person4", "40.0"]];

or

var json = [["ID4", "Person4", "40"], ["ID1", "Person1", "10.0"]];

Upvotes: 1

Views: 1587

Answers (1)

Denys Séguret
Denys Séguret

Reputation: 382514

You could do

json = json.filter(function(v) { return filter.indexOf(v[0])!==-1 })

But I'd recommend you to avoid naming json a variable not holding some JSON.

If you want to be compatible with IE8, I'd recommend to use a shim for filter and indexOf or simply to iterate using 2 for loops.

Upvotes: 2

Related Questions