我有一个JavaScript数组,如:

[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]

如何将单独的内部数组合并为一个,例如:

["$6", "$12", "$25", ...]

当前回答

let arr = [["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"], ["$0"], ["$15"],["$3"], ["$75"], ["$5"], ["$100"], ["$7"], ["$3"], ["$75"], ["$5"]];
arr = arr.reduce((a, b) => a.concat(b)); // flattened

其他回答

ES6方式:

constflatten=arr=>arr.reduce((acc,next)=>acc.concat(Array.isArray(next)?flatten(next):next),[])常量a=[1,[2,[3,[4],[5]]]]console.log(flatten(a))

对于N次嵌套数组,具有ES3回退的扁平函数的ES5方式:

var flatten=(函数){if(!!Array.prototype.reduce&&!!Arrax.isArray){返回函数(数组){return array.reduce(函数(prev,next){return prev.concat(Array.isArray(next)?flatten(next):next);}, []);};}其他{返回函数(数组){var arr=[];变量i=0;var len=阵列长度;var目标;对于(;i<len;i++){目标=阵列[i];arr=arr.concat((Object.protype.toString.call(target)=='[Object Array]')?展平(目标):目标);}返回arr;};}}());var a=[1,[2,[3,[4,[5]]]];console.log(flatten(a));

我使用这个方法来展开混合数组:(这对我来说似乎最简单)。用较长的版本来解释步骤。

function flattenArray(deepArray) {
    // check if Array
    if(!Array.isArray(deepArray)) throw new Error('Given data is not an Array')

    const flatArray = deepArray.flat() // flatten array
    const filteredArray = flatArray.filter(item => !!item) // filter by Boolean
    const uniqueArray = new Set(filteredArray) // filter by unique values
    
    return [...uniqueArray] // convert Set into Array
}

//较短版本:

const flattenArray = (deepArray) => [...new Set(deepArray.flat().filter(item=>!!item))]
flattenArray([4,'a', 'b', [3, 2, undefined, 1], [1, 4, null, 5]])) // 4,'a','b',3,2,1,5

Codesandbox链接

现代方法

使用[].flat(Infinity)方法

const nestedArray = [1,[2,[3],[4,[5,[6,[7]]]]]]
const flatArray = nestedArray.flat(Infinity)
console.log(flatArray)
/**
* flatten an array first level
* @method flatten
* @param array {Array}
* @return {Array} flatten array
*/
function flatten(array) {
  return array.reduce((acc, current) => acc.concat(current), []);
}


/**
* flatten an array recursively
* @method flattenDeep
* @param array {Array}
* @return {Array} flatten array
*/
function flattenDeep(array) {
  return array.reduce((acc, current) => {
    return Array.isArray(current) ? acc.concat(flattenDeep(current)) : acc.concat([current]);
  }, []);
}

/**
* flatten an array recursively limited by depth
* @method flattenDepth
* @param array {Array}
* @return {Array} flatten array
*/
function flattenDepth(array, depth) {
  if (depth === 0) {
    return array;
  }
  return array.reduce((acc, current) => {
    return Array.isArray(current) ? acc.concat(flattenDepth(current, --depth)) : acc.concat([current]);
  }, []);
}

以下代码将压平深度嵌套的数组:

/**
 * [Function to flatten deeply nested array]
 * @param  {[type]} arr          [The array to be flattened]
 * @param  {[type]} flattenedArr [The flattened array]
 * @return {[type]}              [The flattened array]
 */
function flattenDeepArray(arr, flattenedArr) {
  let length = arr.length;

  for(let i = 0; i < length; i++) {
    if(Array.isArray(arr[i])) {
      flattenDeepArray(arr[i], flattenedArr);
    } else {
      flattenedArr.push(arr[i]);
    }
  }

  return flattenedArr;
}

let arr = [1, 2, [3, 4, 5], [6, 7]];

console.log(arr, '=>', flattenDeepArray(arr, [])); // [ 1, 2, [ 3, 4, 5 ], [ 6, 7 ] ] '=>' [ 1, 2, 3, 4, 5, 6, 7 ]

arr = [1, 2, [3, 4], [5, 6, [7, 8, [9, 10]]]];

console.log(arr, '=>', flattenDeepArray(arr, [])); // [ 1, 2, [ 3, 4 ], [ 5, 6, [ 7, 8, [Object] ] ] ] '=>' [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]

有一种比使用上面的答案中列出的merge.contat.apply()方法快得多的方法来实现这一点,我的意思是速度快几个数量级。这假设您的环境可以访问ES5 Array方法。

var array2d = [
  ["foo", "bar"],
  ["baz", "biz"]
];
merged = array2d.reduce(function(prev, next) {
    return prev.concat(next);
});

这里是jsperf链接:http://jsperf.com/2-dimensional-array-merge