简体   繁体   English

在 JavaScript 中展平嵌套数组

[英]Flattening nested array in JavaScript

I have a horrible looking array which looks like this:我有一个看起来很可怕的数组,看起来像这样:

EDIT:编辑:

array = [
    {
        Letters: [{ Letter: 'A' }, { Letter: 'B' }, { Letter: 'C' }],
        Numbers: [{ Number: '1' }, { Number: '2' }, { Number: '3' }]
    },
    null,
    {
        Letters: [{ Letter: 'D' }, { Letter: 'E' }, { Letter: 'F' }, { Letter: 'G' }, { Letter: 'H' }],
        Numbers: [{ Number: '4' }, { Number: '5' }, { Number: '6' }, { Number: '7' }]
    }
];

And want the array to look like this:并希望数组看起来像这样:

flattenedArray = [a,b,c,1,2,3,d,e,f,g,h,4,5,6,7]

Unfortunately I cannot change the original formatting because that is the form received when merging two API responses that I am getting.不幸的是,我无法更改原始格式,因为这是合并我得到的两个 API 响应时收到的表单。

I have tried using:我试过使用:

var flattenedArray = [].concat.apply([], array);

But it just presents the array in the same format it was entered in.但它只是以与输入相同的格式显示数组。

I was wondering if anybody had any advice?我想知道是否有人有任何建议?

EDIT: I have tried implementing the suggestions given - thank you so much for your help.编辑:我已经尝试实施给出的建议 - 非常感谢您的帮助。 It seems it is a problem with the format of the list - unfortunately using the chrome console which is in a 'tree' format I cannot see the direct structure of the array output.似乎这是列表格式的问题 - 不幸的是,使用“树”格式的 chrome 控制台我看不到数组输出的直接结构。

Thank you for all your help!谢谢你的帮助! EDIT 2: See above for the actual array, thank you for showing me how to see this!编辑 2:请参阅上面的实际数组,感谢您向我展示如何查看此内容!

If you have lodash , you can use: 如果你有lodash ,你可以使用:

_.flattenDeep(array)

You can also checkout their source code for ides on how to implement yourself if you prefer. 如果您愿意,您还可以查看有关如何实现自己的ide 的源代码

You can create recursive function using forEach() that will return new array. 您可以使用将返回新数组的forEach()创建递归函数。

 var array = [[['a','b','c'],[1,2,3]],[],[['d','e','f','g','h'],[4,5,6,7]]] function flat(data) { var r = [] data.forEach(e => Array.isArray(e) ? r = r.concat(flat(e)) : r.push(e)); return r; } console.log(flat(array)) 

You can also use reduce() instead of forEach() 您也可以使用reduce()而不是forEach()

 var array = [[['a','b','c'],[1,2,3]],[],[['d','e','f','g','h'],[4,5,6,7]]] function flat(data) { return data.reduce((r, e) => Array.isArray(e) ? r = r.concat(flat(e)) : r.push(e) && r, []) } console.log(flat(array)) 

As @Bergi suggested you can use reduce() like this. 正如@Bergi建议你可以像这样使用reduce()

data.reduce((r, e) => r.concat(Array.isArray(e) ? flat(e) : [e]), [])

Edit for the new request of nested arrays/objects and the flattening, you could use a combined approach with testing for the type of an element. 编辑嵌套数组/对象的新请求和展平,您可以使用组合方法测试元素的类型。

 var array = [{ Letters: [{ Letter: 'A' }, { Letter: 'B' }, { Letter: 'C' }], Numbers: [{ Number: '1' }, { Number: '2' }, { Number: '3' }] }, null, { Letters: [{ Letter: 'D' }, { Letter: 'E' }, { Letter: 'F' }, { Letter: 'G' }, { Letter: 'H' }], Numbers: [{ Number: '4' }, { Number: '5' }, { Number: '6' }, { Number: '7' }] }], result = array.reduce(function iter(r, a) { if (a === null) { return r; } if (Array.isArray(a)) { return a.reduce(iter, r); } if (typeof a === 'object') { return Object.keys(a).map(k => a[k]).reduce(iter, r); } return r.concat(a); }, []); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

Old request and the immortal question how to flat a nested array. 旧请求和不朽的问题如何平展嵌套数组。

 var flat = (r, a) => Array.isArray(a) ? a.reduce(flat, r) : r.concat(a), inputArray = array = [[['a', 'b', 'c'], [1, 2, 3]], [], [['d', 'e', 'f', 'g', 'h'], [4, 5, 6, 7]]], outputArray = inputArray.reduce(flat, []); console.log(outputArray); 

You could try the flatten function in Ramda . 您可以尝试Ramda中flatten功能。

  R.flatten([1, 2, [3, 4], 5, [6, [7, 8, [9, [10, 11], 12]]]]);
    //=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

It's nice to use a recursive function for such cases: 在这种情况下使用递归函数很好:

 arr = [[['a','b','c'],[1,2,3]],[],[['d','e','f','g','h'],[4,5,6,7]]]; function flatten(arr) { var result = []; for (var i = 0, len = arr.length; i < len; i++) { result = result.concat(Array.isArray(arr[i])? flatten(arr[i]) : [arr[i]]); } return result; } console.log(flatten(arr)); 

Your Array format is not correct, you are missing commas(,) . 您的数组格式不正确,您缺少commas(,) This is correct array. 这是正确的数组。

var array = [[['a','b','c'],[1,2,3]],[],[['d','e','f','g','h'],[4,5,6,7]]];

 var array = [[['a','b','c'],[1,2,3]],[],[['d','e','f','g','h'],[4,5,6,7]]]; var result = flatten(array); function flatten(array) { var flat = []; if(array !== undefined){ var flat = []; for (var i = 0; i < arguments.length; i++) { if (arguments[i] instanceof Array) { flat = flat.concat(flatten.apply(null, arguments[i])); } else { flat.push(arguments[i]); } } } return flat; } console.log(result); 

No one thought of splicing in-place? 没人想到就地拼接?

function flatten(array){
    for (var i = 0; i < array.length; i++) {
        if(array[i] instanceof Array){
            array.splice.apply(array,[i,1].concat(array[i]));
            i--;
        }
    };
    return array;
}

One iteration, no recursion. 一次迭代,没有递归。

function steamrollArray(arr) {
  var tmp = [];
  arr.forEach(function(val){
    if(Array.isArray(val))
      tmp = tmp.concat(steamrollArray(val));
    else
      tmp.push(val);
  });

  console.log(tmp);
  return tmp;
}

steamrollArray([1, [2], [3, [[4]]]]);
let arr = [1,2,[3,4]]

/* let newarr = arr.flat(); */

let newarr = Object.values(arr);
let arr2 = []
for(let val of Object.values(arr)) {
         if(!Array.isArray(val)){
     console.log(val)
     arr2.push(val)
     }    
           for ( let val2 of Object.values(val)){
             arr2.push(val2)
           }
}
console.log(arr2)

Implement flatten function using recursion and spread operator.使用递归和扩展运算符实现展平功能。

 const a = [1,[2,[3,4],[5]],6]; const flatten = (arr) => { const res = [] for(let i=0;i<arr.length;i++) { if(!Array.isArray(arr[i])) res.push(arr[i]); else res.push(...flatten(arr[i])); } return res; } console.log(flatten(a));<\/code><\/pre>

"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM