【问题标题】:Jquery Combine Array of Arrays in another Array of ArraysJquery将数组数组合并到另一个数组数组中
【发布时间】:2020-10-08 20:02:51
【问题描述】:

我有这个数组:

arr = [[1,a],[1,b],[2,c],[2,d],[3,e],[3,f]];

...我想把它变成这样:

arr = [[1,a,b],[2,c,d],[3,e,f]];

我猜这是一个“for循环”,但我不知道该怎么做。感谢您的帮助。

【问题讨论】:

    标签: javascript jquery arrays for-loop


    【解决方案1】:

    希望对您有所帮助,我已将值替换为字符串以获得最小的解决方案。

    let arr = [[1,'a'],[1,'b'],[2,'c'],[2,'d'],[3,'e'],[3,'f']];
    
    arr.forEach(function(key, index){
      key.push(arr[index+1][1]);
      arr.splice(index+1, 1);
    });
    
    console.log(arr);

    【讨论】:

    • 它就像一个魅力!非常好的解决方案,非常简短且非常有效。非常感谢!
    【解决方案2】:

    希望对你有帮助

    arr = [[1,'a'],[1,'b'],[2,'c'],[2,'d'],[3,'e'],[3,'f']];
    
    
    	const newArr = arr.reduce((acc, cur) => {
    	const prev = acc.find(elem => elem[0] === cur[0]);
    
        if(prev) {
            prev[1] += ", " + cur[1];
        } 
        else {
            acc.push(cur);
        }
        return acc;
    	}
    	, []);
    
    console.log(newArr);

    【讨论】:

    • 感谢您的回答。
    【解决方案3】:

    您可以使用reduce。在回调函数内部检查累加器是否有键。如果没有,则创建密钥并为其添加值

    let arr = [
      [1, 'a'],
      [1, 'b'],
      [2, 'c'],
      [2, 'd'],
      [3, 'e'],
      [3, 'f']
    ];
    
    let data = arr.reduce((acc, curr) => {
    
      if (!acc[curr[0]]) {
        acc[curr[0]] = [];
      }
      curr.forEach((item) => {
        if (acc[curr[0]].indexOf(item) === -1) {
          acc[curr[0]].push(item);
        }
      })
      return acc;
    }, {});
    console.log(Object.values(data))

    【讨论】:

    • 感谢您的回答。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-28
    • 1970-01-01
    • 2015-11-11
    • 1970-01-01
    • 1970-01-01
    • 2011-07-09
    • 1970-01-01
    相关资源
    最近更新 更多