daily

Common encounter, the same id of two arrays into an array problem

grammar

arr.reduce(function(prev,cur,index,arr){... }, init);Copy the code

Arr stands for primitive array;

Prev represents the return value from the last call to the callback, or the initial value init;

Cur represents the array element currently being processed;

Index represents the index of the array element being processed, 0 if init is provided, 1 otherwise;

Init represents the initial value.

Note that there are only two parameters commonly used: prev and CUR

Merge two arrays by ID

let arr1 = [{ id: 1.age: '14'}, {id: 2.age: '23'}, {id: 3.age: '33' }]
let arr2 = [{ id: 3.name: 'zhangsan'}, {id: 1.name: 'lisi'}, {id: 2.name: 'wangwu' }]
const list = arr2.reduce((prev, cur) = > {
  const target = prev.find(e= > e.id === cur.id);
  if (target) {
    Object.assign(target, cur);
  } else {
    prev.push(cur);
  }
  return prev;
}, arr1);
console.log(list)
Copy the code

TaId merges two arrays by id

let arr1 = [{ taId: 1.age: '14'}, {taId: 2.age: '23'}, {taId: 3.age: '33' }]
let arr2 = [{ id: 3.name: 'zhangsan'}, {id: 1.name: 'lisi'}, {id: 2.name: 'wangwu' }]
const list = arr2.reduce((prev, cur) = > {
  const target = prev.find(e= > e.taId === cur.id);
  if (target) {
    Object.assign(target, cur);
  } else {
    prev.push(cur);
  }
  return prev;
}, arr1);
console.log(list)
Copy the code

Merge two arrays by id