使用在每个子数组的第一个元素中找到的子字符串作为键,将子数组合并。

6

有这样一个二维数组:

arr = [
        ["12325-a", 1, 1, 1],
        ["43858-b", 3, 4, 1],
        ["84329-a", 6, 5, 2],
        ["18767-b", 0, 9, 0],
        ["65888-b", 5, 4, 4],
];

每个子数组的第一个元素都是一个字符串。

我想要将具有相同结尾的子数组组合在一起。在这种情况下,它将被分为两组: -a-b

数值应该根据索引的和进行计算。

因此,结果应该如下所示:

arr = [
        ["-a", 7, 6, 3],
        ["-b", 8, 17, 5],
];

我的解决方案(无法实现):

let arr = [
  ["12325-a", 1, 1, 1],
  ["43858-b", 3, 4, 1],
  ["84329-a", 6, 5, 2],
  ["18767-b", 0, 9, 0],
  ["65888-b", 5, 4, 4],
];

result = arr.reduce(function(acc, curr) {
  if (acc[curr[0].substr(curr[0].length - 2)]) {
    acc[curr[0]] = acc[curr[0]].map(function(val, index) {

      if (index) {
        return val + curr[index];
      }
      return val;
    });
  } else {
    acc[curr[0]] = curr;
  }
  return acc;
}, {});

console.log(result)

3个回答

4

您可以先使用 reduce 方法创建一个对象,然后使用 Object.values 获取值数组。

const arr = [
    ["12325-a", 1, 1, 1],
    ["43858-b", 3, 4, 1],
    ["84329-a", 6, 5, 2],
    ["18767-b", 0, 9, 0],
    ["65888-b", 5, 4, 4],
];

const result = arr.reduce((r, [str, ...rest]) => {
  let key = str.split(/(\d+)/).pop();
  if(!r[key]) r[key] = [key, ...rest];
  else rest.forEach((e, i) => r[key][i + 1] += e)
  return r;
}, {})

console.log(Object.values(result))


3
您在检查现有数据是否存在值并映射现有数据时没有使用正确的键。您的解决方案应如下所示:

let arr = [
  ["12325-a", 1, 1, 1],
  ["43858-b", 3, 4, 1],
  ["84329-a", 6, 5, 2],
  ["18767-b", 0, 9, 0],
  ["65888-b", 5, 4, 4],
];

result = arr.reduce(function(acc, curr) {

  const key = curr[0].substr(curr[0].length - 2);
  console.log(key)
  if (acc[key]) {
    acc[key] = acc[key].map(function(val, index) {

      if (index) {
        return val + curr[index];
      }
      return val;
    });
  } else {
    acc[key] = [curr[0].substr(curr[0].length - 2), ...curr.slice(1)]
  }
  return acc;
}, {});

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


0

使用对象来创建一个对象,其中第一个字符串的最后两个字符将成为键。该键的值将是一个数组,其中包含下一组值。

在第二种情况下,如果对象已经有了该键,则获取索引并将值与其相加。

最后,您可以执行Object.values以获得一个数组

let arr = [
  ["12325-a", 1, 1, 1],
  ["43858-b", 3, 4, 1],
  ["84329-a", 6, 5, 2],
  ["18767-b", 0, 9, 0],
  ["65888-b", 5, 4, 4],
];

let x = arr.reduce(function(acc, curr) {
  // getting last two characters from first string
  let getSubstring = curr[0].slice(-2);
   //checking if object has a key with this name.
   // if not then create it
  if (!acc.hasOwnProperty(getSubstring)) {
    acc[getSubstring] = [];
    // now iterate over the rest of the values and push them
    for (let i = 1; i < curr.length; i++) {
      acc[getSubstring].push(curr[i])
    }
  } else {
     // if already a key exist then create an array of the elements except the first value
    let newArray = curr.splice(1, curr.length);
    newArray.forEach(function(item, index) {
      acc[getSubstring][index] = acc[getSubstring][index] + item

    })
  }
  return acc;
}, {});

for (let keys in x) {
  x[keys].unshift(keys)
}
console.log(Object.values(x))


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接