Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript index of for multiple values

Im having a multdimensional javascript arrays like this.

[
["9", "16", "19", "24", "29", "38"],
["9", "15", "19", "24", "29", "38"],
["10", "16", "19", "24", "29", "38"],
["9", "16", "17", "19", "24", "29", "39"],
["10", "16", "17", "19", "24", "29", "39"],
["9", "15", "21", "24", "29", "38"]

.......
.......
]

Around 40 to be exact

and im having an another array called check with the following values

 [9,10] //This is of size two for example,it may contain any number of elements BUT it only contains elements(digits) from the multidimensional array above

What i want is i need to make the multidimensional array unique based for the check array elements

1.Example if check array is [15] Then multidimensional array would be

[
    ["9", "15", "19", "24", "29", "38"],
   //All the results which contain 15

]

2.Example if check array is [15,21] Then multidimensional array would be

[
    ["9", "15", "21", "24", "29", "38"]
    //simply containing 15 AND 21.Please note previous example has only 15 in it not 21
    //I need an AND not an OR

]

I had tried the JavaScript IndexOf method BUt it is getting me an OR'ed result not AND

Thanks in Advance

like image 289
coolguy Avatar asked Aug 09 '12 10:08

coolguy


2 Answers

Using .filter and .every, you can filter the rows for which every argument is apparent in the row:

var filter = function(args) {
  return arr.filter(function(row) {
    return args.every(function(arg) {
      return ~row.indexOf(String(arg));  // [15] should search for ["15"]
    });
  });
};

.every effectively does an AND operation here; for OR you could use .some instead. Those array functions are available on newer browsers.

like image 23
pimvdb Avatar answered Sep 28 '22 18:09

pimvdb


You can use the .filter() method:

var mainArray = [ /* your array here */ ],
    check = ["15", "21"],
    result;

result = mainArray.filter(function(val) {
    for (var i = 0; i < check.length; i++)
        if (val.indexOf(check[i]) === -1)
            return false;    
    return true;
});

console.log(result);

Demo: http://jsfiddle.net/nnnnnn/Dq6YR/

Note that .filter() is not supported by IE until version 9, but you can fix that.

like image 86
nnnnnn Avatar answered Sep 28 '22 17:09

nnnnnn