【问题标题】:Delete repeated and concatenate values Javascript [closed]删除重复和连接值Javascript [关闭]
【发布时间】:2020-01-22 20:28:31
【问题描述】:

我有这个数组

const array1 = ['546546546546', '01/01/2020', 'A']; 
const array2 = ['866465465465', '01/01/2020', 'B'];
const array3 = ['546546546546', '05/01/2020', 'B'];

array1 和 Array3 的第一个值相同。但其余的就不一样了。

我想消除那些在值 0 中重复的内容,并将它们在 1 和 2 中的内容连接起来。

要得到这样的东西:

['546546546546', '01/01/2020 A - 05/01/2020 B']; 
['866465465465', '01/01/2020 B']; 

【问题讨论】:

  • “我想消除那些……” 但你有没有尝试过?如果是,请在此处发布您的代码尝试,然后我们可以帮助您解决您可能遇到的问题
  • 你希望你的输出是一个数组?有一个对象不是更好,其中键是arrayX[0],值是连接的字符串吗?此外,如果 array3 的值与其他值相同,您想对它做什么也不是很清楚,请将其设置为 null?请edit您的问题,不清楚,也没有显示代码工作量。

标签: javascript arrays


【解决方案1】:

您可以使用数组中的第一个元素作为键来创建字典。我用Array.prototype.reduce创建了一个字典,最后用Object.values从字典中提取值会得到你的结果

const array1 = ['546546546546', '01/01/2020', 'A'];
const array2 = ['866465465465', '01/01/2020', 'B'];
const array3 = ['546546546546', '05/01/2020', 'B'];
// group it into a single array for looping
const input = [array1, array2, array3];

const groupedValues = input.reduce((group, [key, date, name]) => {
  // if exist concat the date and name with previous value
  if (group[key]) {
    group[key][1] = `${group[key][1]} - ${date} ${name}`;
  } else {
    // initialize if doesnt exist
    group[key] = [key, `${date} ${name}`];
  }

  return group;
}, {});

const output = Object.values(groupedValues);

console.log(output);

【讨论】:

    猜你喜欢
    • 2020-06-23
    • 1970-01-01
    • 2012-10-03
    • 2019-06-02
    • 2013-06-21
    • 2018-08-16
    • 2013-10-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多