我有一个JavaScript数组,如:

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

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

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

当前回答

[1,[2,3],[4,[5,6]]].reduce(function(p, c) {
    return p.concat(c instanceof Array ? 
                    c.reduce(arguments.callee, []) : 
                    [c]); 
}, []);

其他回答

如果您的数组仅由整数或字符串组成,则可以使用这种肮脏的方法:

var arr = [345,2,[34],2,[524,[5456]],[5456]];
var flat = arr.toString().split(',');

Works,在FF、IE和Chrome中还没有测试其他浏览器。

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

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)

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

// 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]

如果您的编码环境支持ES6(ES2015),那么您不需要编写任何递归函数或使用map、reduce等数组方法。

一个简单的排列运算符(…)将帮助您将一个数组展平为单个数组

eg:

  const data = [[1, 2, 3], [4, 5],[2]]
  let res = []
  data.forEach(curSet=>{
      res = [...res,...curSet]
  })
  console.log(res) //[1, 2, 3, 4, 5, 2]
let arr = [1, [2, 3, [4, 5, [6, 7], [8, 9, 10, 11, 12]]]];

function flattenList(nestedArr) {
  let newFlattenList = [];

  const handleFlat = (array) => {
    let count = 0;
    while (count < array.length) {
      let item = array[count];
      if (Array.isArray(item)) {
        handleFlat(item);
      } else {
        newFlattenList.push(item);
      }
      count++;
    }
  };
  handleFlat(nestedArr);
  return newFlattenList;
}`enter code here`

console.log(flattenList(arr));

CodeSandBox链接