6

How I can compare two arrays in AngularJS, and return the matching values?

Here is the first array:

[{
    "id":2,
    "student_name":"LiSa",
    "alien":"A",
    "world":"Sun",
    "justification":"i like sent this one",
    "submit_time":null
},{
    "id":1,
    "student_name":"Liz",
    "alien":"B",
    "world":"Earth",
    "justification":null,
    "submit_time":"2014-09-25T08:37:34.526-05:00"
}]

Here is the second one:

[{
    "id":1,
    "alien":"A",
    "world":"Sun",
    "color":"red"
},{
    "id":2,
    "alien":"A",
    "world":"Mercury",
    "color":"red"
},{
    "id":3,
    "alien":"B",
    "world":"Earth",
    "color":"red"
},{
    "id":4,
    "alien":"B",
    "world":"Moon",
    "color":"red"
}]

I want to check if the values for alien and world are matching in these two arrays. Then I can get the color value from the second array.

Here is the code I put in the controller:

angular.forEach(arr1, function(value1, key1) {
    angular.forEach(arr2, function(value2, key2){
        if(value1.alien === value2.alien && value1.world === value2.world){
            console.log(value2.color);

        }
    });
});

Shall I use angular.forEach? How can I do that? And where do I store the color value?

2
  • These are not multi-dimensional arrays (which is an array of arrays), but simply arrays of objects. You should try to explain your question in more detail, it is not obvious what you are trying to compare / test for. Commented Mar 18, 2015 at 22:31
  • Thanks for the comments, @duncanhall I am trying to get the color value when both alien and world are equal in array1 and array2. I modified the question, does it make sense? Commented Mar 19, 2015 at 2:42

2 Answers 2

12

Like duncan said, these are both arrays of objects and not multi-dimensional arrays. Here I use angulars .forEach method to loop through both arrays then compare the object properties.

I've added a comment where you would get your matching color.

angular.forEach(arr1, function(value1, key1) {
    angular.forEach(arr2, function(value2, key2) {
        if (value1.alien === value2.alien && value1.world === value2.world) {
            // here is where you grab the value2.color
        }
    });
});

Here's a fiddle

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the quick answer, but for some reason, it did not work.
Got it, there is one extra ")" in my code. now it works, thank u!
2

And if you are using ES6 then:

array1.forEach((elem1, index) => {elem1;
  array2.forEach((elem2, index) => {elem2;
    if(elem1.someProp=== elem2.someProp)
    {
     //--If elem1 equal elem2
    }
  });
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.