0

Would be really grateful for any help. Im pretty new to javascript and cant figure out how to solve this problem that I am having. Basically I have 2 arrays. One contains an object with an id value and a corresponding group value. The second array contains only the id. I would like to compare the ids of both the arrays and if they match I would like to extract the corresponding group value.

E.g.

a = [1,2,3,4,5];

b = [{1:group1},{2:group2},{3:group3}];

If id in a matches id in b then print out the id's group value

var a = [];
var b = [];
var c = {};


if (condition) {
   c  = {id:group}
   b.push(c)

}

if (condition) {
   a.push(id)

}

for (var i = 0; i < a.length; i++) {
   //If id value in a exists in b, get id's corresponding group value from b
}
1
  • 1
    b[a[i]] should work! If it's undefined, a[i] wasn't in b. Commented Jun 8, 2017 at 13:42

2 Answers 2

1
function find() {    
   for (var i = 0; i < a.length; i++) {
      for (var j = 0; j < b.length; j++) {
         if (b[j].hasOwnProperty(a[i])) {
            return b[j][a[i]];
         }
      }
   }
}
Sign up to request clarification or add additional context in comments.

Comments

1

An alternative solution:

<script>
a = [
    1, // index 0
    2, // index 1
    3, // index 2
    4, // index 3
    5  // index 4
];

b = [
    {1:'group1'}, // index [0][1]
    {2:'group2'}, // index [1][2]
    {3:'group3'} // index [2][3]
];

// If id in a matches id in b then print out the id's group value
var i = 1;
for (var key in b) {
    var bKeys = Object.keys(b[key]);

    if(bKeys[0] == a[key]) {
        console.log(b[key][i]);
    }

  i++;
}
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.