Damien
Damien

Reputation: 4319

Filter Multi-dimension array based on matching string

I have a Multi-Dimension Array filled with products. I'm trying to filter my products by passing a bunch of values and then put the resulting products into a new array. Here's what i'm trying to accomplish:

products = [['A','2','F','123'],['A','2','G','234'],['B','2','K','231']];
related = [];

filter1 = 'A';
filter2 = '2';
filter3 = 'G';

for(var i = 0; i < products.length; i++) {
  var product = products[i];
  for(var j = 0; j < product.length; j++) {
    if(filter1=product[0]){
      related.push([product[0],product[1]....]);
    }
  }
}

Then from there, filter the resulting set with filter2 and so on and so forth. Can't seem to figure this out. Any help is greatly appreciated!

Upvotes: 0

Views: 35

Answers (2)

TaoPR
TaoPR

Reputation: 6052

There are some suggestions I would add as follows:

1) Your outmost loop starts from i=1 instead of i=0, so the first element won't get filtered.

2) When you want a set of multiple filters to be applied, you should consider using an array for more convenience.

3) To add a new element to the array, use push, not the = assignment.

So let's try this:

products = [['A','2','F','123'],['A','2','G','234'],['B','2','K','231']];
related = [];

filters = ['A','2','G'];

for (var product of products) {
    var matchAllFilter = true;
    for (var f of filters){
        if (product.indexOf(f)<0){
            matchAllFilter = false;
            break;
        }
    }    
    if (matchAllFilter){
        related.push(product);
    }
}

Upvotes: 0

sfletche
sfletche

Reputation: 49774

There's a few things going on here...

First, it looks like you want the Array.prototype.push along with the apply functions which can be used together to append the contents of an array onto another array (rather than appending the array as a single unit).

Array.prototype.push.appy(related, product);

Additionally, you want to use === for checking equality (the single = is for assignment only).

for(var i = 1; i < products.length; i++) {
  var product = products[i];
  if(filter1 === product[0] && filter2 === product[1] && filter3 === product[2]){
    Array.prototype.push.appy(related, product);
  } 
}

Upvotes: 1

Related Questions