1

I have two arrays of objects.Where each object has different properties, Like this

    let array1=[
    {id:121122,name:"Matt Jeff"},
    {id:121123,name:"Philip Jeff"}, 
    {id:121124,name:"Paul Jeff"}]
    
    let array2=[
    {owner_id:121122,id:1211443,value:18},
    {owner_id:121127,id:1211428,value:22}]

How can I check if the owner_id in the array2 is equal to the id in array1 then return the new array like this

let newArray=[
{owner_id:121122,id:1211443,value:18}
]

Where the owner_id in array2 is equal to the id in array1.

3 Answers 3

1

If I correctly understand what you need, you could do like this:

let array1 = [{
    id: 121122,
    name: "Matt Jeff"
  }, {
    id: 121123,
    name: "Philip Jeff"
  }, {
    id: 121124,
    name: "Paul Jeff"
  }
]

let array2 = [{
    owner_id: 121122,
    id: 1211443,
    value: 18
  }, {
    owner_id: 121127,
    id: 1211428,
    value: 22
  }
]

const result = array2.filter(({ owner_id }) => array1.some(({ id }) => id === owner_id));

console.log(result);

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

Comments

0

You could try with nested for like:

let array1=[
    {id:121122,name:"Matt Jeff"},
    {id:121123,name:"Philip Jeff"}, 
    {id:121124,name:"Paul Jeff"}]
    
    let array2=[
    {owner_id:121122,id:1211443,value:18},
    {owner_id:121127,id:1211428,value:22}];
    
let result = [];

for(let i = 0; i < array1.length; i++) {
   for(let j = 0; j < array2.length; j++) {
      if (array1[i].id === array2[j].owner_id) {
         result.push(array2[j]);
      }
   }
}

console.log(result)

Comments

0

EFFICIENT WAY: Using Set and filter

O(m) - Iterating on array1 and Storing the id in Set

O(n) - Iterating on the array2 and filtering the result which include O(1) to search in Set;

let array1 = [
  { id: 121122, name: "Matt Jeff" },
  { id: 121123, name: "Philip Jeff" },
  { id: 121124, name: "Paul Jeff" },
];

let array2 = [
  { owner_id: 121122, id: 1211443, value: 18 },
  { owner_id: 121127, id: 1211428, value: 22 },
];

const dict = new Set();
array1.forEach((o) => dict.add(o.id));

const result = array2.filter((o) => dict.has(o.owner_id));

console.log(result);

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.