【问题标题】:Group items with the same value in Array在 Array 中对具有相同值的项目进行分组
【发布时间】:2018-10-12 16:26:08
【问题描述】:

例如,我有一个对象数组

const data = [
 {color: "green", number: 23}, 
 {color: "red", number: 25}, 
 {color: "green", number: 27}, 
 {color: "green", number: 26}, 
 {color: "orange", number: 30}
];

我想根据一个值对相同的项目进行分组,但前提是它们一个接一个并进行下拉。如果中间有什么,那就没有。例如,这看起来像这样。

green
red
green (2)
orange

如果我点击有两个项目的绿色,它会同时显示两个项目,如果我再次点击它,它只会显示数字。我尝试使用引导下拉菜单做一些事情,但运气不佳。如果它们只是一个接一个,而不是它们之间有一些价值,我该如何对它们进行分组?

【问题讨论】:

  • 展示你的尝试

标签: javascript arrays reactjs loops dictionary


【解决方案1】:

由于您尚未提供任何工作代码,让我为您提供一些代码,我相信您将能够从那里构建您的引导程序。

您的原始数据

const data = [
 {color: "green", number: 23}, 
 {color: "red", number: 25}, 
 {color: "green", number: 27}, 
 {color: "green", number: 26}, 
 {color: "orange", number: 30}
];

让我们初始化变量...

let previousItemColor = false;
let newData = [];

遍历我们的原始数据...

data.map((item, index) => {
    // Does our last iteration was about the same color ? ?

    // Yes ! ✨
    if (item.color === previousItemColor) {
        // Remove the last entry from newData and store it in lastItem
        let lastItem = newData.pop();
        // Append the new item into lastItem elements property
        lastItem.elements.push(item)
        // Push that modified entry into newData array
        newData.push(lastItem);
    }

    // Oh! That's a new entry ?
    else {
        let newEntry = {
            groupName: item.color,
            elements: [item]
        };
        newData.push(newEntry);
    }

    // Don't forget, we need to store that color into peviousItemColor, so our script know what was the last iteration.
    previousItemColor = item.color;
});

让我们检查一下我们是否走对了……

console.log(newData);

预期结果:

data = [
    {groupName: "green", elements: [{color: green, number: 23}]},
    {groupName: "red", elements: [{color: red, number: 25}]},
    {groupName: "green", elements: [{color: green, number: 27}, {color: green, number: 26}]},
    {groupName: "orange", elements: [{color: orange, number: 30}]}
];

由于我们现在有可用的数据,我们可以构建任何我们喜欢的下拉菜单...

newData.map((item, index) => {
        console.log(`${item.groupName} ${(item.elements.length > 1 ? item.elements.length : '')}`);
});

预期结果:

green
red
green 2
orange

使用这种方法,您仍然可以保留一开始拥有的所有数据,以便您可以在下拉列表中创建子项。

附注我知道还有另一种方法可以解决它,但由于 O.P. 看起来很新,让我们让它走得更远,让他/她了解整个过程。

【讨论】:

  • 你好乔纳森,非常感谢您的详细解释。这非常有效。
猜你喜欢
  • 2020-08-14
  • 1970-01-01
  • 1970-01-01
  • 2023-03-09
  • 1970-01-01
  • 2023-04-02
  • 1970-01-01
  • 1970-01-01
  • 2013-02-05
相关资源
最近更新 更多