有没有一种简单的方法可以使嵌套数组扁平化

Is there an easy way to make nested array flat?

本文关键字:可以使 方法 嵌套 数组 扁平化 简单 一种 有没有      更新时间:2023-09-26
就是

要做这个:

[ ['dog','cat', ['chicken', 'bear'] ],['mouse','horse'] ]

到:

['dog','cat','chicken','bear','mouse','horse']

var flattened = [[0, 1], [2, 3], [4, 5]].reduce(function(a, b) {
  return a.concat(b);
});
// flattened is [0, 1, 2, 3, 4, 5]

值得注意的是,在IE 8及更低版本中不支持reduce。

developer.mozilla.org 参考

资料

在现代浏览器中,您可以在没有任何外部库的情况下在几行中执行此操作:

Array.prototype.flatten = function() {
  return this.reduce(function(prev, cur) {
    var more = [].concat(cur).some(Array.isArray);
    return prev.concat(more ? cur.flatten() : cur);
  },[]);
};
console.log([['dog','cat',['chicken', 'bear']],['mouse','horse']].flatten());
//^ ["dog", "cat", "chicken", "bear", "mouse", "horse"]

Grab 下划线.js并使用 flatten 函数。

_.flatten([ ['dog','cat', ['chicken', 'bear'] ],['mouse','horse'] ]);

这一个班轮代码呢?

console.log([['dog', 'cat', ['chicken', 'bear']], [['mouse', 'horse'], 'lion']].join().split(','));

基本上加入将使逗号分隔的字符串与嵌套数组分开,使用拆分可以获得 1D 数组,很好吗?奖金它也可以在所有主要浏览器上运行:)

ChewOnThis_Trident解决方案的小修复,它工作得很好:

Array.prototype.flatten = function() {
    return this.reduce(function(a, b) {
        return a.concat(b);
    }, []);
};

假设一个数组已经从 JSON 中解压缩,请尝试以下操作:

Array.prototype.flatten = function() {
    var r = [];
    for (var i = 0; i < this.length; ++i) {
        var v = this[i];
        if (v instanceof Array) {
            Array.prototype.push.apply(this, v.flatten());
        } else {
            r.push(v);
        }
    }
    return r;
};

它似乎在您的输入上正常工作 - 请参阅 http://jsfiddle.net/alnitak/Ws7L5/

现在在2019年,您可以轻松地使用任何深度的Array.flat

let arr  = [ ['dog','cat', ['chicken', 'bear'] ],['mouse','horse'] ]
let op = arr.flat(Infinity)
console.log(op)

现在,如果您想获得唯一值,您可以同时组合设置和平面

let arr  = [ ['dog','cat', ['chicken', 'bear', 'cat'] ],['mouse','horse', 'dog'], [[[['deeper','chicken']]]] ]
let unique  = [...new Set(arr.flat(Infinity))]
console.log(unique)
浏览器可比性 除了IE之外,所有其他似乎都支持IE,您可以使用polyfill。

我知道

这已经晚了,但我也遇到了需要将多维数组制作成 1 个数组的情况,我做了一个函数,如下所示。

function nested(arr) {
    var noNest = arr.toString().split(',').filter(Boolean),
        i = 0;
    for(i;i<noNest.length; i++){
        if(isNaN(noNest[i])){
            return console.log(noNest);
        } else {
            noNest[i] = parseInt(noNest[i]);
        }
    }
    return console.log(noNest);
}
nested([[['a']], [['b']]]);

这也将嵌套数组置于测试数组中,并确保其一个数组作为最终输出

这个解决方案对我来说效果很好,我发现它特别容易遵循:

function flattenArray(arr) {
  // the new flattened array
  var newArr = [];
  // recursive function
  function flatten(arr, newArr) {
    // go through array
    for (var i = 0; i < arr.length; i++) {
      // if element i of the current array is a non-array value push it
      if (Array.isArray(arr[i]) === false) {
        newArr.push(arr[i]);
      }
      // else the element is an array, so unwrap it
      else {
        flatten(arr[i], newArr);
      }
    }
  }
  flatten(arr, newArr);
  return newArr;
}

这就是为什么我喜欢javascript:

function flattenArray(source) {
  return source.toString().split(',');
}
flattenArray([['dog', 'cat', ['chicken', 'bear']], ['mouse', 'horse']]);
// -> ['dog','cat','chicken','bear','mouse','horse']

展平任何深度的对象的最简单方法是使用平面方法

var arr = [['dog','cat', ['chicken', 'bear']],[['mouse','horse'],'lion'] ]; 
var flattened = arr.flat(Infinity);
//output--> ["dog", "cat", "chicken", "bear", "mouse", "horse", "lion"]

更多 aout Flat()

ES6 的方法是

[['a', 'b'], ['c', 'd']].reduce((x,v) => [...x, ...v], [])
相关文章: