JavaScript检查重复项并添加重复ID

时间:2019-09-04 19:32:24

标签: javascript arrays

我有以下数组

s=123456789

尝试将两个Test1合并到一个vals数组中,以便最终数组具有

const prod = [
  {name:'Test1',vals:[12]},
  {name:'Test1', vals:[14]},
  {name:'Test2', vals:[19]}
   //other array items
 ]

所以我尝试过

 const finalprod = [
  {name:'Test1',vals:[12,14]},
  {name:'Test2', vals:[19]}
   //other array items
 ]

我被困在如何进行上。我如何继续获得最终阵列?

5 个答案:

答案 0 :(得分:2)

您可以这样做:

SELECT Workorder.ArrivalDate
FROM JobWorkOrders
WHERE TRY_CONVERT(DATE, Workorder.ArrivalDate, 101) IS NULL;

答案 1 :(得分:2)

使用reduce而不是forEach,在累加器中查找该项目(如果存在),将val与当前元素合并,否则将其推入累加器:

const prod = [
  {name:'Test1',vals:[12]},
  {name:'Test1', vals:[14]},
  {name:'Test2', vals:[19]}   
 ]

const finalprod = prod.reduce((acc, curr) => {
  const ndx = acc.findIndex(e => e.name === curr.name);

  if (ndx > -1)
    acc[ndx].vals = [...acc[ndx].vals, ...curr.vals];
  else
    acc.push(curr);

  return acc;
}, []);

console.log(finalprod);

答案 2 :(得分:1)

您可以使用reduceMap

  • 在数组上使用name作为键
  • 如果键Map中已经存在该键,请通过将当前值附加到该键来更新其值。
  • 如果不存在,请使用当前键将当前值作为初始值添加到Map

const prod = [{name:'Test1',vals:[12]},{name:'Test1', vals:[14]},{name:'Test2', vals:[19]}]

let final = prod.reduce((op,{name,vals}) => {
  if(op.has(name)){
    op.set(name, {name, val:op.get(name).vals.concat(vals) })
  } else{
    op.set(name, {name,vals} )
  }
  return op
},new Map)

console.log([...final.values()])

答案 3 :(得分:1)

您可以使用Array.reduce创建名称及其值的映射,并使用Array.map将其转换为所需的形状。代码中的其他注释。

const prod = [{name:'Test1',vals:[12]},{name:'Test1', vals:[14]},{name:'Test2', vals:[19]}];
 
//Combine the values into an object, e.g. { Test1: [12,14], Test2: [19] }
const hash = prod.reduce((out, {name,vals}) => ({  //for each item in array
  ...out,                                          //append to existing map
  [name]: (out[name] || []).concat(vals)           //combine like names
}), {});

//Transform above obj into the desired shape
const result = Object.keys(hash).map(key => ({     //for each key
  name: key,                                       //set "name" to the key name
  vals: hash[key]                                  //and "vals" to the associated value
}));
  
console.log(result);

答案 4 :(得分:1)

您可以创建一个对象以合并名称值,然后将其转换为所需的数组

const prod = [{
    name: 'Test1',
    vals: [12]
  },
  {
    name: 'Test1',
    vals: [14]
  },
  {
    name: 'Test2',
    vals: [19]
  },
];

const ret = Object.entries(prod.reduce((tmp, x) => {
  tmp[x.name] = (tmp[x.name] || []).concat(x.vals);

  return tmp;
}, {})).map(([x, y]) => ({
  name: x,
  vals: y,
}));

console.log(ret);