0

I have two arrays.

The first Array:

let array1 = [
   {label:'john', value:1},
   {label:'susan', value:2},
   {label:'ann', value:3}
 ]

The second Array:

let array2 = [
 {id:1, name:'john', age:12},
 {id:3, name:'ann', age:24}
]

What am looking forward is to get all the array1 objects which value matches with id in array2

So basically the solution should have:

{label:'john', value:1}
{label:'ann', value:3}

So I have tried:

let matches  = [];
 array1.forEach((item1)=>{
   array2.forEach((item2)=>{
    if(item2.id === item1.value){
      matches.push() //stuck here 

   }
  })

})

Am stuck on how to push the items to a new array. Also looking at my code it looks abit messy. How do i refactor the code to work .

1
  • Do you want to match the value with the id only? Meaning, would {id:1, name:'hubert', age:99} in the second array still be considered a “match” for {label:'john', value:1} from the first? Commented Feb 2, 2018 at 12:34

2 Answers 2

4

You could filter array2 and take only the objects where value matches id in array2.

Methods:

  • Array#filter for filtering an array, retuns a new array with itmes where the callback returns a truthy value,

  • Array#find, which searches for an item, which meet the condition.

  • destructuring assignment, like { value } for getting only the property with that name.

var array1 = [{ label: 'john', value: 1 }, { label: 'susan', value: 2 }, { label: 'ann', value: 3 }],
    array2 = [{ id: 1, name: 'john', age: 12 }, { id: 3, name: 'ann', age: 24 }],
    result = array1.filter(({ value }) =>
        array2.find(({ id }) => 
            value === id
        )
    );
    
console.log(result);

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

1 Comment

i think the readability is not good.Does that mean i am still not familiar with ES6? or the readability is truly not good
2

Try the following:

let array1 = [
   {label:'john', value:1},
   {label:'susan', value:2},
   {label:'ann', value:3}
 ]

let array2 = [
 {id:1, name:'john', age:12},
 {id:3, name:'ann', age:24}
]
var matches = [];
array1.forEach(function(item1){
  array2.forEach(function(item2){
    if(item1.value == item2.id)
      matches.push(item1)
  });
});
console.log(matches);

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.