0

I compare id with two array with object.

Here is my function:

array1 = [
{ id: 1 },
{ id: 2 },
{ id: 3 }
];

array2 = [
{ id: 1 },
{ id: 2 },
{ id: 3 }
];

const compareFunction = (array1, array2) => {
  array2.map((allValue) => {
    array1.map((value) => {
      allValue.selected = value.id === allValue.id;
    });
  })

 return array2;
}

I think I will get the array2 like

[{ id: 1, selected: true }, { id: 2, selected: true },{ id: 3, selected: true }]

but actually array2 become

[{ id: 1, selected: false }, { id: 2, selected: false },{ id: 3, selected: true }]

Only the last array argument selected become true.

Which step was wrong ? Thanks.

4
  • 1
    What's the logic you're looking for? Do you want selected to be true if the id at one index matches the id at the same index in the other array, or what? Commented Dec 14, 2019 at 9:41
  • Yes, my array1 sometime will be [{ id: 1 }] or [{ id: 1 }, { id: 2 }] or [{ id: 1 }, { id: 2 }, { id: 3 }] Commented Dec 14, 2019 at 9:44
  • Sounds like it might be a bit different - are the objects always in order, or are you just trying to see if an object with the same ID exists? (eg, if one array is [{ id: 2 }, { id: 3 }], would you want no selecteds, or two?) Commented Dec 14, 2019 at 9:45
  • allValue will be for-each loop value -> { id: 1 } { id: 2 } { id: 3 } Commented Dec 14, 2019 at 9:46

2 Answers 2

6

Convert the 2nd array to a Set of id values. Iterate the 1st array with a Array.map() and create a new object for each item, by spreading the current object, and adding the selected value. To get the selected value check if the Set contains that current item id.

const array1 = [{ id: 1 },{ id: 2 },{ id: 3 }];
const array2 = [{ id: 1 },{ id: 2 },{ id: 3 }];

const a2Set = new Set(array2.map(o => o.id))

const result = array1.map(o => ({ ...o, selected: a2Set.has(o.id) }))

console.log(result)

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

Comments

1

checkout this :

array1 = [{ id: 1 },{ id: 2 },{ id: 3 }];
array2 = [{ id: 1 },{ id: 2 },{ id: 3 }];



const compareFunction = (array1, array2) => {

  const result = [];
  array2.forEach(arr2item => {
      let selected = false;
      for(let arr1item of array1){
          selected = arr1item.id === arr2item.id;
          if(selected)break;
      }
      result.push({id : arr2item.id , selected : selected});
  });

  return result;
}

console.log(compareFunction(array1 , array2));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.