简体   繁体   中英

How to update values not present in one array of objects from another array of objects?

I have two arrays of objects which contain a huge amount of data. The structure of these two arrays goes something like this.

arr1 = [
  {x: 1, y: '2018-01-01'}, 
  {x: 2, y: '2018-01-02'},           
  {x: 3, y: '2018-01-03'},
  {x: 5, y: '2018-01-05'},
....
]
arr2 = [
  {x: 1, y: '2018-01-01'}, 
  {x: 2, y: '2018-01-02'},           
  {x: 3, y: '2018-01-03'},
  {x: 4, y: '2018-01-04'},
  {x: 5, y: '2018-01-05'},
  {x: 6, y: '2018-01-08'}
]

I want to update arr2 in such a way that it updates the array of objects with values that are only present in arr1 and drop any values not present in arr1. Note, I want to update the original arr2 and not return a new array.

I tried iterating through individual arrays and remove values not present but not luck.

You could get a map and iterate from the end for splicing unknown items or update changed values.

 var arr1 = [{ x: 1, y: '2018-01-01x' }, { x: 2, y: '2018-01-02' }, { x: 3, y: '2018-01-03' }, { x: 5, y: '2018-01-05' }], arr2 = [{ x: 1, y: '2018-01-01' }, { x: 2, y: '2018-01-02' }, { x: 3, y: '2018-01-03' }, { x: 4, y: '2018-01-04' }, { x: 5, y: '2018-01-05' }, { x: 6, y: '2018-01-08' }], map = arr1.reduce((m, { x, y }) => m.set(x, y), new Map), i = arr2.length; while (i--) { if (map.has(arr2[i].x)) { if (map.get(arr2[i].x) !== arr2[i].y) { arr2[i].y = map.get(arr2[i].x); } } else { arr2.splice(i, 1); } } console.log(arr2); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM