Home > Net >  Given two array create another one with only different element
Given two array create another one with only different element

Time:11-17

I have two array:

for example:

arraySelectedItems = [{id: 1, name: "item1"}, {id: 2, name: "item2"}]
arraySavedItems = [{id: 1, name: "item1"}, {id: 2, name: "item2"}]

now I need to check if there is some item in arraySavedItems that is not present in arraySelectedItems, and in this case I'll go to populate another array called arrayDeletedItems.

If the two arrays have the same items I don't need to populate the arrayDeletedItems.

So I have tried with this code:

arraySavedItems.filter((itemSaved) => !arraySelectedItems.find((itemSel) => {
  if (itemSaved.id !== itemSel.id) {
    arrayDeletedItems.push(itemSaved)
  }
}
))

So with this data:

 arraySelectedItems = [{id: 1, name: "item1"}, {id: 2, name: "item2"}]
 
 arraySavedItems = [{id: 1, name: "item1"}, {id: 2, name: "item2"}]

I'll expect that arrayDeletedItems will be:

 arrayDeletedItems = []

Instead whit this data for example:

 arraySelectedItems = [{id: 1, name: "item1"}]

 arraySavedItems = [{id: 1, name: "item1"}, {id: 2, name: "item2"}]

I'll expect that arrayDeletedItems will be:

arrayDeletedItems = [{id: 2, name: "item2"}]

With my code I receive and arrayDeletedItems that has the all values:

arrayDeletedItems = [{id: 1, name: "item1"}, {id: 2, name: "item2"}]

CodePudding user response:

Consider this generic function:

function difference(a, b, keyFn) {
    let keys = new Set(a.map(keyFn))
    return b.filter(obj => !keys.has(keyFn(obj)))
}


//


selectedItems = [{id: 1, name: "item1"}, {id:4}]

savedItems = [{id: 1, name: "item1"}, {id: 2, name: "item2"}, {id:3}, {id:4}]

result = difference(selectedItems, savedItems, obj => obj.id)

console.log(result)

CodePudding user response:

You can use the .includes() method on an array to check whether a value is contained in it (see the documentation for more information).

Now we can just filter the array of saved items to find only ones that aren't contained by the selected items array.

arrayDeletedItems = arraySavedItems.filter((itemSaved) => 
  !arraySelectedItems.includes(itemSaved)
)

CodePudding user response:

To solve this problem, since we have id we can utilize it. You need a key that is unique. so id commonly known will have unique value.

So my approach, find items that is not exist in B array but in A array, and find items that exist in B but not in A array.

This approach not be the fastest, but the findDiff is reusable.

const a = [....];
const b = [....];

const findDiff = (source, target) => {
   return source.filter((sourceItem, index) => {
      const isInTarget = target.findIndex(targetItem => targetItem.id === sourceItem.id)
      return isInTarget === -1
   })
}
const difference = findDiff(a,b).concat(findDiff(b,a)); //result
  • Related