我有一个JavaScript数组,如:

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

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

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

当前回答

我只是尝试在不使用任何内置函数的情况下解决这个问题。

var arr = [1, 3, 4, 65, [3, 5, 6, 9, [354, 5, 43, 54, 54, 6, [232, 323, 323]]]];
var result = [];

function getSingleArray(inArr) {
  for (var i = 0; i < inArr.length; i++) {
    if (typeof inArr[i] == "object") {
      getSingleArray(inArr[i]); // Calling Recursively
    } else {
      result.push(inArr[i]);
    }
  }
}

getSingleArray(arr);
console.log(result); // [1, 3, 4, 65, 3, 5, 6, 9, 354, 5, 43, 54, 54, 6, 232, 323, 323]

其他回答

我写的简单的flatten util

const flatten = (arr, result = []) => {
    if (!Array.isArray(arr)){
        return [...result, arr];
    }
     arr.forEach((a) => {
         result = flatten(a, result)
    })

    return result
}

console.log(flatten([1,[2,3], [4,[5,6,[7,8]]]])) // [ 1, 2, 3, 4, 5, 6, 7, 8 ]
/**
* 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 flatten(obj) {
    var out = [];
    function cleanElements(input) {
        for (var i  in input){
            if (input[i]instanceof Array){
                cleanElements(input[i]);
            }
            else {
                out.push(input[i]);
            }
        }
    }
    cleanElements(obj);
    return (out);
}

如何使用JavaScript 1.8的reduce(callback[,initialValue])方法

list.reduce((p,n) => p.concat(n),[]);

能胜任这项工作。

简单并处理多个嵌套级别:

// deeply nested array
const myArray = [1, 2, [3, 4, [5, 6, [[[7,8, [[[[[9, 10]]]]]]]]]]] ;

const flatten = (arr) => {
    for (let index = 0; index < arr.length; index++) {
        const elem = arr[index];

        if (Array.isArray(elem)) {
            arr.splice(index, 1, ...elem);
            index--;
        }
    }
};

flatten(myArray);
console.log(myArray); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]