1

Hello Im trying to compare 2 array of object

and here is my code

const arr1 = [
{id:1,active:true},
{id:3,active:true},
{id:6,active:true},
{id:7,active:true},
]


const arr2 = [
{id:1,active:false},
{id:2,active:false},
{id:3,active:false},
{id:4,active:false},
{id:5,active:false},
{id:6,active:false},
{id:7,active:false},

]

let res = [] 

let ids = arr1.forEach((item) => {
          return arr2.map((keyRow) => {
            if (keyRow.id === item.id) {
              keyRow.active = true
            }
            res.push(keyRow) 
          })
        })


console.log(res)

the proplem with this code is output double of array size my expected result is

[
{id:1,active:true},
{id:2,active:false},
{id:3,active:true},
{id:4,active:false},
{id:5,active:false},
{id:6,active:true},
{id:7,active:true}
]

how do I can achive that

2 Answers 2

2

Map the second larger array, and inside the callback, check to see the ID being iterated over has an active property present in the first:

const arr1 = [
{id:1,active:true},
{id:3,active:true},
{id:6,active:true},
{id:7,active:true},
];
const actives = new Set(arr1.filter(item => item.active).map(item => item.id));


const arr2 = [
{id:1,active:false},
{id:2,active:false},
{id:3,active:false},
{id:4,active:false},
{id:5,active:false},
{id:6,active:false},
{id:7,active:false},
]

const newArr = arr2.map(item => (
  actives.has(item.id)
  ? ({ id: item.id, active: true })
  : item
));
console.log(newArr);

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

1 Comment

thank you for your enlightment, I thougt I can achive only with forEach in the begining
1

  const arr1 = [
    { id: 1, active: true },
    { id: 3, active: true },
    { id: 6, active: true },
    { id: 7, active: true }
  ];

  const arr2 = [
    { id: 1, active: false },
    { id: 2, active: false },
    { id: 3, active: false },
    { id: 4, active: false },
    { id: 5, active: false },
    { id: 6, active: false },
    { id: 7, active: false }
  ];

  let res = [];

  let ids = arr1.forEach((item) => {
    return arr2.map((keyRow) => {
      if (keyRow.id === item.id) {
        keyRow.active = true;
        res.push(keyRow);
      }
    });
  });

  console.log(res);

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.