javascript - 如何将对象数组映射到具有重复值标识符的数组?

标签 javascript arrays object

使用像这样的对象数组:

const data = [
  {count: 400, value: "Car Wash Drops"},
  {count: 48, value: "Personal/Seeding"},
  {count: 48, value: "Personal/Seeding"},
];

我想映射到一个带有重复值附加标识符的数组:

const expected = [
  ["Car Wash Drops", 400],
  ["Personal/Seeding (1)", 48],
  ["Personal/Seeding (2)", 48],
];

到目前为止,我有一个映射函数来相应地映射值,但我不确定如何继续为重复项附加标识符。

data.map(d => [`${d.value}`, d.count]);

结果:

[
  ["Car Wash Drops", 400],
  ["Personal/Seeding", 48],
  ["Personal/Seeding", 48],
]

我也使用了索引,但它在每个值上都添加了索引:

data.map((d, i) => [`${d.value} ${i}`, d.count]);

结果:

[
  ["Car Wash Drops (0)", 400],
  ["Personal/Seeding (1)", 48],
  ["Personal/Seeding (2)", 48],
]

最佳答案

使用您的方法,您可以在 map 内部使用 filter() 来检查原始数组中有多少元素与当前分析的元素具有相同的值,使用此条件您可以选择要作为新值返回:

const data = [
  {count: 400, value: "Car Wash Drops"},
  {count: 48, value: "Personal/Seeding"},
  {count: 48, value: "Personal/Seeding"},
];

let res = data.map((x, idx) =>
{
    if (data.filter(y => y.value === x.value).length > 1)
        return [`${x.value} (${idx})`, x.count];
    else
        return [`${x.value}`, x.count];
});

console.log(res);

如果我们使用 some() 而不是 filter() 可以提高之前方法的性能,如下所示:

const data = [
  {count: 400, value: "Car Wash Drops"},
  {count: 48, value: "Personal/Seeding"},
  {count: 48, value: "Personal/Seeding"},
  {count: 300, value: "Operators/Management"},
  {count: 48, value: "Personal/Seeding"}
];

let res = data.map((x, idx) =>
{
    if (data.some((y, j) => y.value === x.value && idx !== j))
        return [`${x.value} (${idx})`, x.count];
    else
        return [`${x.value}`, x.count];
});

console.log(res);

如果我们之前创建一个 Map 可以进一步改进带有元素出现在原始数组中的次数的计数器。像这样:

const data = [
  {count: 400, value: "Car Wash Drops"},
  {count: 48, value: "Personal/Seeding"},
  {count: 48, value: "Personal/Seeding"},
  {count: 300, value: "Operators/Management"},
  {count: 48, value: "Personal/Seeding"}
];

let counters = data.reduce((res, {value}) =>
{
    res.set(value, res.has(value) ? res.get(value) + 1 : 1);
    return res;
}, new Map());

let res = data.map((x, idx) =>
{
    return [
        `${x.value}` + (counters.get(x.value) > 1 ? `(${idx})` : ""),
        x.count
    ]; 
});

console.log(res);

关于javascript - 如何将对象数组映射到具有重复值标识符的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54221759/

相关文章:

javascript - Node.js : Regex to make sure the string is the first in the line

javascript - Javascript 中的全局变量生命周期

javascript - 将具有相同键的嵌套对象合并到 JavaScript 中的单个对象中

javascript - Sequelize中如何进行算术运算?

javascript - 为什么文本没有像应有的那样更改为 'Testinghi'?

java - 数组和具体化类型

javascript - 如何减去对象数组中具有相似键的对象值? (不要与删除重复项混淆)

arrays - 在perl中找出数组中元素的数量

javascript - 如何将并行列表的对象转换为对象列表?

javascript - 如何使用 JavaScript 设置 future X 天?