-1

I have array something like this:

var array1 = [
          {"name":"a","groups":["xxx","yyy"]},
          {"name":"abc","groups":["xxx","yyy"]},
          {"name":"abcd","groups":["zzz","xxx","yyy"]}
        ];

and

var array2 = ["xxx","yyy"];

I need to return the entire index of array1 when both "xxx" and "yyy" of array2 matches only to the "xxx" and "yyy" of array1.

Like in this example, it should only return array1[0] and array1[1]. Any help will be greatly appreciated. Thank you.

  • 1
    Why don't you write a program to do that? –  Feb 18 '15 at 04:38
  • -1 because you haven't shown any indication that you've actually given this a go before asking the question here, and it looks suspiciously like you're just trying to get people to do your homework for you. – Joel Cox Feb 18 '15 at 05:32
  • what makes you think that I haven't spent two days on this? All my approaches results for "or" operations. I couldn't figure out of to get the "and" (intersection) operation. I'm not asking you to do my work. Even the solutions here are not helping but yes i'm getting ideas and thats all i was seeking help for. So please stop judging! – srikar sastry Feb 18 '15 at 05:40

3 Answers3

2

Modern JS would be:

function filter(array1, array2) {              // to filter array1 based on array2
  return array1.filter(function(elt) {         // retain an elt in array1
    var groups = elt.groups;                   // if its groups property
    return groups.length === array2.length &&  // has the same length as array2
      groups.every(function(e) {               // and every element in it
        return array2.indexOf(e) > -1;         // is found in array2
      });
  });
}

var array1 = [
          {"name":"a","groups":["xxx","yyy"]},
          {"name":"abc","groups":["xxx","yyy"]},
          {"name":"abcd","groups":["zzz","xxx","yyy"]}
        ];
var array2 = ["xxx","yyy"];

document.writeln(JSON.stringify(filter(array1, array2)));
  • Thank you so so much for this. It worked like charm. People complained that I'm asking for others to do my work but the problem is not this simple. I cant share the code which is so decoupled that cannot be written in jsfiddle or plnkr. Anyways, thank you so much sir. – srikar sastry Feb 18 '15 at 15:00
  • In my case, i needed to get back the array not a string so I added JSON.parse() at the end. – srikar sastry Feb 18 '15 at 15:01
0
var array1 = [
          {"name":"a","groups":["xxx","yyy"]},
          {"name":"abc","groups":["xxx","yyy"]},
          {"name":"abcd","groups":["zzz","xxx","yyy"]}
        ];


var array2 = ["xxx","yyy"];

function checkArrays( arrA, arrB ){
    //check if lengths are different
    if(arrA.length !== arrB.length) return false;
    //slice so we do not effect the orginal
    //sort makes sure they are in order
    var cA = arrA.slice().sort(); 
    var cB = arrB.slice().sort();
    for(var i=0;i<cA.length;i++){
         if(cA[i]!==cB[i]) return false;
    }
    return true;
}



for (var i in array1){
    if (checkArrays(array1[i].groups, array2)){
        alert(array1[i]);
    }
}

http://jsfiddle.net/hh1tyy5e/

JavaScript does not have built in list comparison method.
Anyways, above is working code that will alert the desired elements from array1

taesu
  • 4,482
  • 4
  • 23
  • 41
  • Not recommended to use `for...in` to iterate across arrays. –  Feb 18 '15 at 04:54
  • Why is that? in this case, it's absolutely fine? if it was required to other operations on indexes, then no I wouldnt have used it. – taesu Feb 18 '15 at 04:55
  • @taesu http://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-such-a-bad-idea for one – jdphenix Feb 18 '15 at 04:57
  • In this particular case, there is no room for error. I am aware why it is not a good practice. Do you guys have any argument in particular to this question? – taesu Feb 18 '15 at 05:01
  • @torazburo, read it yourself. `for..in should not be used to iterate over an Array where index order is important.` index order is not important as you don't care about indexes. You only care about current index. – taesu Feb 18 '15 at 05:02
  • If you have a javascript library that adds functions using Array.prototype your for..in will fail. – James Feb 18 '15 at 05:09
  • No, we have no particular argument with your solution. We're just picking at minor points. I'm not quite sure why you're so insistent that it's OK to use `for in` here. It's not. Your code will fail code review at any software development company. It will fail in the face of any enumerable method added to the `Object` prototype, as another commenter pointed out. The issue of order is just one reason to avoid this, not the only one. –  Feb 18 '15 at 05:12
0

I used stringify for comparison so the code doesn't change for a generic "something inside an object property" (ie the content of "groups" - or whatever) - performance could be better if you use direct compares.

var array1 = [
  {"name":"a","groups":["xxx","yyy"]},
  {"name":"abc","groups":["xxx","yyy"]},
  {"name":"abcd","groups":["zzz","xxx","yyy"]}
];

var testgroup = ["xxx", "yyy"];
var tg = JSON.stringify(testgroup);

var filteredArray = array1.filter(function (el) {
    if (JSON.stringify(el.groups) == tg) return el;
});
alert(JSON.stringify(filteredArray));
James
  • 20,957
  • 5
  • 26
  • 41
  • Not a good idea to use `stringify`. Also, this will fail if the elements are in different order. Why are you returning `el` from the filter function, instead of just returning the boolean result of the comparison? Why are you stringifying `testgroup` over and over again each time through the loop? –  Feb 18 '15 at 04:49
  • Elements should be placed in the correct order before we get to this point - in a SQL order by clause - javascript is a poor choice for sorting easily database-ordered data. By all means sort testgroup to match using javascript. Since you asked why - I am returning el from the filter function because I forgot to change it from my array.map function I snarfed it from. Other than clarity and adding a few characters there's no real reason to change it. And yeah I guess I could stringify testgroup once. – James Feb 18 '15 at 05:01
  • You have no idea where this data is coming from, and if by some chance it **is** coming from SQL, you have no idea how it's coming and may not (probably do not) have access to the SQL code that is generating it. Then again, assuming the input is already sorted could be a good idea if your idea of fun is fixing bugs six months later in code that you had forgotten you had written. I'm not sure why you would say "JS is a poor choice" for sorting. This is 2015, not 2002. JS could sort that array in a few microseconds. On my machine, it sorted it one million times in just over a millisecond. –  Feb 18 '15 at 05:04
  • Sorting the data is beyond the scope of the question. At the very least it should be ascertained whether or not it is necessary, which is not clear, before writing pointless sorting algorithms. – James Feb 18 '15 at 05:09
  • Sorting the data is absolutely **not** beyond the scope of a question which is about comparing the elements in two arrays. No one is suggesting writing pointless sorting algorithms. We're suggesting using `Array#sort` to sort the arrays before comparing their elements, as other answers to this question correctly do. –  Feb 18 '15 at 05:21
  • i get the data from API and yes I don't the order will stay the same all the time. I dont think stringify is a good idea too. – srikar sastry Feb 18 '15 at 05:44