Widdesto Yudistiro
Widdesto Yudistiro

Reputation: 63

comparing 2 array javascript

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

Upvotes: 1

Views: 99

Answers (2)

FreePhoenix888
FreePhoenix888

Reputation: 6157

  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);

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 371233

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);

Upvotes: 2

Related Questions