JavaScript:如何基于字段在数组中添加和排序相同的字段?

时间:2019-08-06 01:45:01

标签: javascript arrays

我有如下所示的数组a:

var a = [
  {name: 'phone' , id:1 ,num:1},
  {name: 'milk' ,id:2, num:1},
  {name: 'apple' , id:3 , num:1},
  {name: 'phone', id: 4, num:3},
]

我想按数组名称过滤并添加自己的num

var currentName = a[0]
let newArrys=[]
for(let i = 0; i<a.length;i++){
   if(currentName.name == a[i].name){
       a[i].num = a[i].num + currentName.num
       let tmepArry = [];
        tempArry.push(a[i]);
        newArrys.push(tempArry);
   }
}

我正在尝试获取以下2D数组:

[
 [{name: 'phone', id:1, num:4}],
 [{name: 'milk',id:2, num:1}],
 [{name: 'apple', id: 3 num:1}]
]

结果无法筛选出来。

我的尝试无效。

你能帮我吗?

3 个答案:

答案 0 :(得分:3)

给出:

var a = [
  {name: 'phone' , id:1 ,num:1},
  {name: 'milk' ,id:2, num:1},
  {name: 'apple' , id:3 , num:1},
  {name: 'phone', id: 4, num:3},
]
const newArrys = a.reduce((acc, current) => {
  // find an object in the array with a matching name
  const existing = acc.find(obj => obj.name === current.name);
  if (existing) {
    // combine the numbers
    existing.num += current.num;
  } else {
    acc.push(current);
  }
  return acc;
}, []).map(obj => [obj])

这将为您提供所需的东西。

答案 1 :(得分:1)

这是一个简单的例子。从本质上讲,这是一个两步过程,涉及到首先将您的对象数组简化为带有计数(数字)的不同列表。然后,遍历结果以创建2D数组。

通过向化简器添加更多代码,可能有一种更奇特的方法来产生相同的结果,但是此处尝试提高可读性,因为在化简函数中很容易迷失。

var a = [
  {name: 'phone' , id:1 ,num:1},
  {name: 'milk' ,id:2, num:1},
  {name: 'apple' , id:3 , num:1},
  {name: 'phone', id: 4, num:3},
]

// Get the counts using reduce
const results = a.reduce( (acc, curr) => {
	if (acc.hasOwnProperty(curr.name)) {
  	acc[curr.name].num += curr.num;
  } else {
  	acc[curr.name] = {id: curr.id, num: curr.num };
  }
  return acc;
}, {});

// Establish result array
const finalResult = [];
// Iterate over results object and format them into an array of a single object
// then push the array to the finalResult array (thus making it 2D)
for (const key in results) {
	const item = results[key];
	finalResult.push([{ name: key, id: item.id, num: item.num }]);
}

console.log(finalResult);

答案 2 :(得分:0)

不确定这是否是最佳解决方案,但它确实有效。请随时为我应该做的事情提供建议,以获得更好的代码。哈哈..

var a = [
  {name: 'phone' , id:1 ,num:1},
  {name: 'milk' ,id:2, num:1},
  {name: 'apple' , id:3 , num:1},
  {name: 'phone', id: 4, num:3},
]

function organize_array(tmpArray) {
  let data = []
  tmpArray.forEach(function(value, key) {
      if(data.filter(tmp => tmp.name == value.name) == '') {
        const tmpFiltered = a.filter(tmp => tmp.name == value.name)
        let total = 0
        tmpFiltered.map(x => { total += x.num })
        data.push({name: value.name, num: total})
      }
  })
  return data
}

console.log(organize_array(a))