首页 > 解决方案 > 如何对数组进行分类并形成新数组

问题描述

在我的项目中,我需要对一个数组进行分类并将其转换为另一种类型的数组。我遇到的困难是没有办法使用简洁高效的执行。以下是我的输入和输出:

const input = [{
    "type": 1,
    "color": "Red(268)"
  },
  {
    "type": 1,
    "color": "Blue(583)"
  },
  {
    "type": 2,
    "color": "Blue(185)"
  },
  {
    "type": 4,
    "color": "Red(326)"
  },
  {
    "type": 4,
    "color": "Blue(967)"
  },
  {
    "type": 5,
    "color": "Red(863)"
  }
]
const output = [
  "Type 1: Red(268), Blue(583)",
  "Type 2: Blue(185)",
  "Type 4: Red(326), Blue(967)",
  "Type 5: Red(863)"
]

以下是我的方法。我用set()找出类型的个数,然后用for循环把它转成字符串压入数组,但是不能连续执行,所以我的函数不能得到正确的结果,而且是效率不高。

this.ty = 1;
this.result = [];

const set = new Set();
const length = input.filter(item => !set.has(item.type) ? set.add(item.type) : false).length + 1;

for (let i = 1; i < length; i++) {
  const temp = input.filter(x => {
    return x.type === ty;
  })
  if (temp.length < 2) {
    this.result.push(`Type ${ty}: ${temp[0].color}`);
  } else {
    this.result.push(`Type ${ty}: ${temp[0].color}, ${temp[1].color}`);
  }
  this.ty = i + 1;
}

这个问题困扰了我很久。有人可以提供一种更简单的方法来转换这个数组吗?谢谢您的帮助。

const input = [{
    "type": 1,
    "color": "Red(268)"
  },
  {
    "type": 1,
    "color": "Blue(583)"
  },
  {
    "type": 2,
    "color": "Blue(185)"
  },
  {
    "type": 4,
    "color": "Red(326)"
  },
  {
    "type": 4,
    "color": "Blue(967)"
  },
  {
    "type": 5,
    "color": "Red(863)"
  }
]

console.log('input', input);

this.ty = 1;
this.result = [];

const set = new Set();
const length = input.filter(item => !set.has(item.type) ? set.add(item.type) : false).length + 1;

for (let i = 1; i < length; i++) {
  const temp = input.filter(x => {
    return x.type === ty;
  })
  if (temp.length < 2) {
    this.result.push(`Type ${ty}: ${temp[0].color}`);
  } else {
    this.result.push(`Type ${ty}: ${temp[0].color}, ${temp[1].color}`);
  }
  this.ty = i + 1;
}

console.log('result', this.result);

// output
/* const output = [
  "Type 1: Red(268), Blue(583)",
  "Type 2: Blue(185)",
  "Type 4: Red(326), Blue(967)",
  "Type 5: Red(863)"
] */

标签: javascriptarrays

解决方案


您可以使用Array.reduce()函数来迭代您的数组并构造一个新对象。

const input = [{
    "type": 1,
    "color": "Red(268)"
  },
  {
    "type": 1,
    "color": "Blue(583)"
  },
  {
    "type": 2,
    "color": "Blue(185)"
  },
  {
    "type": 4,
    "color": "Red(326)"
  },
  {
    "type": 4,
    "color": "Blue(967)"
  },
  {
    "type": 5,
    "color": "Red(863)"
  }
];

const mappedInput = input.reduce((grouped, {
  type,
  color
}) => {
  if (!grouped.hasOwnProperty(type)) {
    grouped[type] = `Type ${type}: ${color}`;
  } else {
    grouped[type] += `, ${color}`;
  }
  return grouped;
}, {});

console.log(Object.values(mappedInput));

我们使用一个对象来提供有效的键查找,最后只检索我们需要的字符串数组。


推荐阅读