Scalać/spłaszczać tablicę tablic w JavaScript?

Mam tablicę JavaScript w stylu:

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

Jak mógłbym połączyć oddzielne wewnętrzne tablice w jedną:

["$6", "$12", "$25", ...]
Author: AndrewL, 2012-06-02

30 answers

Możesz użyć concat do scalania tablic:

var arrays = [["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]];
var merged = [].concat.apply([], arrays);

Użycie metody apply z concat pobierze drugi parametr jako tablicę, więc ostatnia linia jest identyczna z tą:

var merged2 = [].concat(["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]);
 1331
Author: Gumbo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-17 09:02:12

Oto krótka funkcja, która wykorzystuje niektóre z nowszych metod tablicy JavaScript do spłaszczenia tablicy n-wymiarowej.

function flatten(arr) {
  return arr.reduce(function (flat, toFlatten) {
    return flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten);
  }, []);
}

Użycie:

flatten([[1, 2, 3], [4, 5]]); // [1, 2, 3, 4, 5]
flatten([[[1, [1.1]], 2, 3], [4, 5]]); // [1, 1.1, 2, 3, 4, 5]
 368
Author: Noah Freitas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-02 17:40:35

Oto proste i wydajne rozwiązanie funkcjonalne:

var result = [].concat.apply([], [[1],[2,3],[4]]);
console.log(result); // [ 1, 2, 3, 4 ]

Żadnego bałaganu.

 275
Author: Nikita Volkov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-20 21:17:24

Najlepiej zrobić to za pomocą javascript reduce function.

var arrays = [["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"], ["$0"], ["$15"],["$3"], ["$75"], ["$5"], ["$100"], ["$7"], ["$3"], ["$75"], ["$5"]];

arrays = arrays.reduce(function(a, b){
     return a.concat(b);
}, []);

Lub, z ES2015:

arrays = arrays.reduce((a, b) => a.concat(b), []);

Js-fiddle

Mozilla docs

 147
Author: user2668376,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-22 07:39:15

Większość odpowiedzi nie działa na wielkich (np. 200 000 elementów) tablicach, a nawet jeśli tak, to są powolne. polkovnikov.ph ODPOWIEDŹ ma najlepszą wydajność, ale nie działa na głębokie spłaszczenie.

Oto najszybsze rozwiązanie, które działa również na tablicach z wieloma poziomami zagnieżdżania :

const flatten = function(arr, result = []) {
  for (let i = 0, length = arr.length; i < length; i++) {
    const value = arr[i];
    if (Array.isArray(value)) {
      flatten(value, result);
    } else {
      result.push(value);
    }
  }
  return result;
};

Przykłady

Wielkie tablice

flatten(Array(200000).fill([1]));

Świetnie radzi sobie z wielkimi tablicami. Na mojej maszynie kod ten zajmuje około 14 ms do wykonać.

Zagnieżdżone tablice

flatten(Array(2).fill(Array(2).fill(Array(2).fill([1]))));

Działa z zagnieżdżonymi tablicami. Kod ten tworzy [1, 1, 1, 1, 1, 1, 1, 1].

Tablice o różnych poziomach zagnieżdżania

flatten([1, [1], [[1]]]);

Nie ma żadnych problemów z spłaszczaniem tablic, takich jak ta.

 55
Author: Michał Perłakowski,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-05 10:12:47

Aktualizacja: okazało się, że to rozwiązanie nie działa z dużymi tablicami. Jeśli szukasz lepszego, szybszego rozwiązania, sprawdź tę odpowiedź .


function flatten(arr) {
  return [].concat(...arr)
}

Jest po prostu rozszerza arr i przekazuje je jako argumenty do concat(), co łączy wszystkie tablice w jedną. Jest odpowiednikiem [].concat.apply([], arr).

Możesz również spróbować tego do głębokiego spłaszczenia:

function deepFlatten(arr) {
  return flatten(           // return shalowly flattened array
    arr.map(x=>             // with each x in array
      Array.isArray(x)      // is x an array?
        ? deepFlatten(x)    // if yes, return deeply flattened x
        : x                 // if no, return just x
    )
  )
}

Zobacz demo na JSBin .

Odniesienia do ECMAScript 6 elementów użytych w tym odpowiedź:


Uwaga na marginesie: metody takie jak find() i funkcje strzałek nie są obsługiwane przez wszystkie przeglądarki, ale nie oznacza to, że nie możesz teraz korzystać z tych funkcji. Wystarczy użyć Babel - przekształca kod ES6 w ES5.

 49
Author: Michał Perłakowski,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:18:30

Możesz użyć podkreślenia :

var x = [[1], [2], [3, 4]];

_.flatten(x); // => [1, 2, 3, 4]
 42
Author: Todd Yandell,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-06-02 18:58:38

Ogólne procedury oznaczają, że nie musimy przepisywać złożoności za każdym razem, gdy musimy użyć określonego zachowania.

concatMap (lub flatMap) jest dokładnie tym, czego potrzebujemy w tej sytuacji.

// concat :: ([a],[a]) -> [a]
const concat = (xs,ys) =>
  xs.concat (ys)

// concatMap :: (a -> [b]) -> [a] -> [b]
const concatMap = f => xs =>
  xs.map(f).reduce(concat, [])

// id :: a -> a
const id = x =>
  x

// flatten :: [[a]] -> [a]
const flatten =
  concatMap (id)

// your sample data
const data =
  [["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]

console.log (flatten (data))

Foresight

I tak, odgadłeś to poprawnie, tylko spłaszcza jeden poziom, który dokładnie tak powinien działać {33]}

Wyobraź sobie taki zestaw danych

// Player :: (String, Number) -> Player
const Player = (name,number) =>
  [ name, number ]

// team :: ( . Player) -> Team
const Team = (...players) =>
  players

// Game :: (Team, Team) -> Game
const Game = (teamA, teamB) =>
  [ teamA, teamB ]

// sample data
const teamA =
  Team (Player ('bob', 5), Player ('alice', 6))

const teamB =
  Team (Player ('ricky', 4), Player ('julian', 2))

const game =
  Game (teamA, teamB)

console.log (game)
// [ [ [ 'bob', 5 ], [ 'alice', 6 ] ],
//   [ [ 'ricky', 4 ], [ 'julian', 2 ] ] ]

Ok, teraz powiedzmy, że chcemy wydrukować lista, która pokazuje wszystkich graczy, którzy będą uczestniczyć w game ...

const gamePlayers = game =>
  flatten (game)

gamePlayers (game)
// => [ [ 'bob', 5 ], [ 'alice', 6 ], [ 'ricky', 4 ], [ 'julian', 2 ] ]

Jeśli nasza flatten procedura spłaszczy zagnieżdżone tablice, skończylibyśmy z tym wynikiem śmieci ...{22]}

const gamePlayers = game =>
  badGenericFlatten(game)

gamePlayers (game)
// => [ 'bob', 5, 'alice', 6, 'ricky', 4, 'julian', 2 ]

Rollin ' deep, baby

Nie oznacza to, że czasami nie chcesz spłaszczać zagnieżdżonych tablic – tylko, że nie powinno to być domyślne zachowanie.

Możemy z łatwością wykonać deepFlatten procedurę ...

// concat :: ([a],[a]) -> [a]
const concat = (xs,ys) =>
  xs.concat (ys)

// concatMap :: (a -> [b]) -> [a] -> [b]
const concatMap = f => xs =>
  xs.map(f).reduce(concat, [])

// id :: a -> a
const id = x =>
  x

// flatten :: [[a]] -> [a]
const flatten =
  concatMap (id)

// deepFlatten :: [[a]] -> [a]
const deepFlatten =
  concatMap (x =>
    Array.isArray (x) ? deepFlatten (x) : x)

// your sample data
const data =
  [0, [1, [2, [3, [4, 5], 6]]], [7, [8]], 9]

console.log (flatten (data))
// [ 0, 1, [ 2, [ 3, [ 4, 5 ], 6 ] ], 7, [ 8 ], 9 ]

console.log (deepFlatten (data))
// [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
Tam. Teraz masz narzędzie do każde zadanie – jedno do zgniatania jednego poziomu zagnieżdżenia, flatten, a jedno do zacierania wszystkich zagnieżdżeń deepFlatten.

Może możesz go nazwać obliterate lub nuke, Jeśli nie podoba ci się nazwa deepFlatten.


Nie powtarzaj dwa razy !

Oczywiście powyższe implementacje są sprytne i zwięzłe, ale użycie .map, po którym następuje wywołanie .reduce oznacza, że robimy więcej iteracji niż jest to konieczne {22]}

Używanie zaufanego kombinatora, który dzwonię mapReduce pomaga utrzymać jeśli jesteś zainteresowany, {66]}napisałem o nich inne odpowiedzi {67]} {22]}

// mapReduce = (a -> b, (b,a) -> b, (b,a) -> b)
const mapReduce = (m,r) =>
  (acc,x) => r (acc, m (x))

// concatMap :: (a -> [b]) -> [a] -> [b]
const concatMap = f => xs =>
  xs.reduce (mapReduce (f, concat), [])

// concat :: ([a],[a]) -> [a]
const concat = (xs,ys) =>
  xs.concat (ys)

// id :: a -> a
const id = x =>
  x

// flatten :: [[a]] -> [a]
const flatten =
  concatMap (id)
  
// deepFlatten :: [[a]] -> [a]
const deepFlatten =
  concatMap (x =>
    Array.isArray (x) ? deepFlatten (x) : x)

// your sample data
const data =
  [ [ [ 1, 2 ],
      [ 3, 4 ] ],
    [ [ 5, 6 ],
      [ 7, 8 ] ] ]

console.log (flatten (data))
// [ [ 1. 2 ], [ 3, 4 ], [ 5, 6 ], [ 7, 8 ] ]

console.log (deepFlatten (data))
// [ 1, 2, 3, 4, 5, 6, 7, 8 ]
 36
Author: user633183,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-28 07:21:38

Rozwiązanie dla bardziej ogólnego przypadku, gdy w tablicy mogą znajdować się elementy inne niż tablica.

function flattenArrayOfArrays(a, r){
    if(!r){ r = []}
    for(var i=0; i<a.length; i++){
        if(a[i].constructor == Array){
            r.concat(flattenArrayOfArrays(a[i], r));
        }else{
            r.push(a[i]);
        }
    }
    return r;
}
 28
Author: Trindaz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-28 01:28:19

Aby spłaścić tablicę tablic pojedynczych elementów, nie trzeba importować biblioteki, prosta pętla jest zarówno najprostszym, jak i najbardziej efektywnym rozwiązaniem:

for (var i = 0; i < a.length; i++) {
  a[i] = a[i][0];
}

Do downvoterów: proszę przeczytaj pytanie, nie pomniejszaj, bo nie pasuje do twojego zupełnie innego problemu. To rozwiązanie jest zarówno najszybsze, jak i najprostsze dla zadanego pytania.

 21
Author: Denys Séguret,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-08 07:20:23

Istnieje nowa natywna metoda ECMA 2018 o nazwie flat , aby to zrobić dokładnie.

const arr1 = [1, 2, [3, 4]];
arr1.flat(); 
// [1, 2, 3, 4]

const arr2 = [1, 2, [3, 4, [5, 6]]];
arr2.flat();
// [1, 2, 3, 4, [5, 6]]
 17
Author: Alister Norris,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-30 12:23:32

Kolejne rozwiązanie ECMAScript 6 w stylu funkcjonalnym:

Funkcja Declare:

const flatten = arr => arr.reduce(
  (a, b) => a.concat(Array.isArray(b) ? flatten(b) : b), []
);

I użyj go:

flatten( [1, [2,3], [4,[5,[6]]]] ) // -> [1,2,3,4,5,6]
 16
Author: diziaq,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-01 10:49:11

A co z użyciem reduce(callback[, initialValue]) Metody JavaScript 1.8

list.reduce( function( p,n){
    return p.concat( n  );
},[]);
 13
Author: rab,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-04-30 11:50:33

Uwaga: Kiedy Function.prototype.apply ([].concat.apply([], arrays)) lub operator spread ([].concat(...arrays)) jest używany do spłaszczenia tablicy, oba mogą powodować przepełnienia stosu dla dużych tablic, ponieważ każdy argument funkcji jest przechowywany na stosie.

Oto implementacja bezpieczna dla stosu w stylu funkcjonalnym, która waży najważniejsze wymagania względem jednego Inny:

  • reusability
  • czytelność
  • zwięzłość
  • wydajność

// small, reusable auxiliary functions:

const foldl = f => acc => xs => xs.reduce(uncurry(f), acc); // aka reduce

const uncurry = f => (a, b) => f(a) (b);

const concat = xs => y => xs.concat(y);


// the actual function to flatten an array - a self-explanatory one-line:

const flatten = xs => foldl(concat) ([]) (xs);

// arbitrary array sizes (until the heap blows up :D)

const xs = [[1,2,3],[4,5,6],[7,8,9]];

console.log(flatten(xs));


// Deriving a recursive solution for deeply nested arrays is trivially now


// yet more small, reusable auxiliary functions:

const map = f => xs => xs.map(apply(f));

const apply = f => a => f(a);

const isArray = Array.isArray;


// the derived recursive function:

const flattenr = xs => flatten(map(x => isArray(x) ? flattenr(x) : x) (xs));

const ys = [1,[2,[3,[4,[5],6,],7],8],9];

console.log(flattenr(ys));

Jak tylko przyzwyczaisz się do funkcji małych strzałek w postaci skróconej, kompozycji funkcji i funkcji wyższego rzędu, kod ten czyta się jak proza. Programowanie polega jedynie na składaniu małych klocków, które zawsze działają zgodnie z oczekiwaniami, ponieważ nie zawierają żadnych skutków ubocznych.

 13
Author: ftor,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-23 16:34:08
const common = arr.reduce((a, b) => [...a, ...b], [])
 11
Author: YairTawil,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-27 08:53:16
var arrays = [["a"], ["b", "c"]];
Array.prototype.concat.apply([], arrays);

// gives ["a", "b", "c"]

(piszę to jako osobną odpowiedź, opartą na komentarzu @danhbear.)

 7
Author: VasyaNovikov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-16 07:32:53

ES6 One Line Flatten

# Patrz lodash flatten, Płaskowyż (płytkie true)

function flatten(arr) {
  return arr.reduce((acc, e) => acc.concat(e), []);
}

Lub

function flatten(arr) {
  return [].concat.apply([], arr);
}

Testowane z

test('already flatted', () => {
  expect(flatten([1, 2, 3, 4, 5])).toEqual([1, 2, 3, 4, 5]);
});

test('flats first level', () => {
  expect(flatten([1, [2, [3, [4]], 5]])).toEqual([1, 2, [3, [4]], 5]);
});

ES6 One Line Deep Flatten

# patrz lodash flattenDeep, underscore flatten

function flattenDeep(arr) {
  return arr.reduce((acc, e) => Array.isArray(e) ? acc.concat(flattenDeep(e)) : acc.concat(e), []);
}

Testowane z

test('already flatted', () => {
  expect(flattenDeep([1, 2, 3, 4, 5])).toEqual([1, 2, 3, 4, 5]);
});

test('flats', () => {
  expect(flattenDeep([1, [2, [3, [4]], 5]])).toEqual([1, 2, 3, 4, 5]);
});
 7
Author: zurfyx,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-22 22:00:19

Jeśli masz tylko tablice z 1 elementem łańcuchowym:

[["$6"], ["$12"], ["$25"], ["$25"]].join(',').split(',');
Wykonam zadanie. Bt, który dokładnie pasuje do twojego przykładu kodu.
 6
Author: Florian Salihovic,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-06-02 19:18:08

Zrobiłem to używając rekurencji i zamknięć

function flatten(arr) {

  var temp = [];

  function recursiveFlatten(arr) { 
    for(var i = 0; i < arr.length; i++) {
      if(Array.isArray(arr[i])) {
        recursiveFlatten(arr[i]);
      } else {
        temp.push(arr[i]);
      }
    }
  }
  recursiveFlatten(arr);
  return temp;
}
 6
Author: balajiv,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-29 12:10:50

Wolałbym przekształcić całą tablicę, as-is, na łańcuch znaków, ale w przeciwieństwie do innych odpowiedzi, zrobiłbym to za pomocą {[1] } i nie używał metody toString(), która generuje niechciany wynik.

Z tym wyjściem JSON.stringify pozostaje tylko usunąć wszystkie nawiasy, ponownie zawinąć wynik nawiasami początkowymi i końcowymi i podać wynik za pomocą JSON.parse, co przywraca łańcuch do "życia".

  • może obsługiwać nieskończone zagnieżdżone tablice bez żadnych kosztów szybkości.
  • może prawidłowo obsługiwać Elementy tablicy, które są łańcuchami zawierającymi przecinki.

var arr = ["abc",[[[6]]],["3,4"],"2"];

var s = "[" + JSON.stringify(arr).replace(/\[|]/g,'') +"]";
var flattened = JSON.parse(s);

console.log(flattened)

  • tylko dla wielowymiarowej tablicy łańcuchów / liczb (Nie obiektów)
 6
Author: vsync,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-02 09:02:14

ES6 sposób:

const flatten = arr => arr.reduce((acc, next) => acc.concat(Array.isArray(next) ? flatten(next) : next), [])

const a = [1, [2, [3, [4, [5]]]]]
console.log(flatten(a))

ES5 sposób dla flatten funkcja z ES3 fallback dla N-razy zagnieżdżonych tablic:

var flatten = (function() {
  if (!!Array.prototype.reduce && !!Array.isArray) {
    return function(array) {
      return array.reduce(function(prev, next) {
        return prev.concat(Array.isArray(next) ? flatten(next) : next);
      }, []);
    };
  } else {
    return function(array) {
      var arr = [];
      var i = 0;
      var len = array.length;
      var target;

      for (; i < len; i++) {
        target = array[i];
        arr = arr.concat(
          (Object.prototype.toString.call(target) === '[object Array]') ? flatten(target) : target
        );
      }

      return arr;
    };
  }
}());

var a = [1, [2, [3, [4, [5]]]]];
console.log(flatten(a));
 6
Author: Artem Gavrysh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-20 10:50:18

Wygląda na to, że to wygląda jak zadanie dla rekurencji!

  • Obsługuje wiele poziomów zagnieżdżania
  • Obsługuje puste tablice i inne parametry
  • nie ma mutacji
  • nie polega na nowoczesnych funkcjach przeglądarki

Kod:

var flatten = function(toFlatten) {
  var isArray = Object.prototype.toString.call(toFlatten) === '[object Array]';

  if (isArray && toFlatten.length > 0) {
    var head = toFlatten[0];
    var tail = toFlatten.slice(1);

    return flatten(head).concat(flatten(tail));
  } else {
    return [].concat(toFlatten);
  }
};

Użycie:

flatten([1,[2,3],4,[[5,6],7]]);
// Result: [1, 2, 3, 4, 5, 6, 7] 
 5
Author: Jai,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-04-01 03:35:37

Po prostu najlepsze rozwiązanie bez lodash

let flatten = arr => [].concat.apply([], arr.map(item => Array.isArray(item) ? flatten(item) : item))
 5
Author: Vlad Ankudinov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-07 10:20:52

Podejście Haskellowskie

function flatArray([x,...xs]){
  return x ? [...Array.isArray(x) ? flatArray(x) : [x], ...flatArray(xs)] : [];
}

var na = [[1,2],[3,[4,5]],[6,7,[[[8],9]]],10];
    fa = flatArray(na);
console.log(fa);
 5
Author: Redu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-01 15:49:26

To nie jest trudne, po prostu iteratuj tablice i łącz je:

var result = [], input = [["$6"], ["$12"], ["$25"], ["$25"], ["$18"]];

for (var i = 0; i < input.length; ++i) {
    result = result.concat(input[i]);
}
 4
Author: Niko,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-06-02 18:56:43

Logika polega na przekonwertowaniu tablicy wejściowej na ciąg znaków i usunięciu wszystkich nawiasów ([]) i przetworzeniu wyjścia na tablicę. Używam do tego funkcji szablonu ES6.

var x=[1, 2, [3, 4, [5, 6,[7], 9],12, [12, 14]]];

var y=JSON.parse(`[${JSON.stringify(x).replace(/\[|]/g,'')}]`);

console.log(y)
 4
Author: R Santosh Reddy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-24 12:42:31

Wygłupiałem się z generatorami ES6 i napisałem ten gist . Który zawiera...

function flatten(arrayOfArrays=[]){
  function* flatgen() {
    for( let item of arrayOfArrays ) {
      if ( Array.isArray( item )) {
        yield* flatten(item)
      } else {
        yield item
      }
    }
  }

  return [...flatgen()];
}

var flatArray = flatten([[1, [4]],[2],[3]]);
console.log(flatArray);

Zasadniczo tworzę generator, który zapętla się nad oryginalną tablicą wejściową, jeśli znajdzie tablicę, używa operatora yield* w połączeniu z rekurencją do ciągłego spłaszczania wewnętrznych tablic. Jeśli element nie jest tablicą, to po prostu daje pojedynczy element. Następnie używając ES6 Spread operator (aka splat operator) spłaszczam generator do nowej instancji tablicy.

Nie testowałem wydajności tego, ale myślę, że jest to ładny prosty przykład użycia generatorów i operatora wydajności*.

Ale znowu, wygłupiałem się, więc jestem pewien, że jest więcej skutecznych sposobów, aby to zrobić.
 3
Author: ashwell,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-28 22:42:39

Proponuję dwa krótkie rozwiązania bez rekurencji. Nie są optymalne z punktu widzenia złożoności obliczeniowej, ale działają dobrze w przeciętnych przypadkach:

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

// Solution #1
while (a.find(x => Array.isArray(x)))
    a = a.reduce((x, y) => x.concat(y), []);

// Solution #2
let i = a.findIndex(x => Array.isArray(x));
while (i > -1)
{
    a.splice(i, 1, ...a[i]);
    i = a.findIndex(x => Array.isArray(x));
}
 3
Author: Tommaso Ognibene,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-30 16:11:53
const flatten = array => array.reduce((a, b) => a.concat(Array.isArray(b) ? flatten(b) : b), []); 

Na żądanie, rozbicie jednej linii oznacza w zasadzie to.

function flatten(array) {
  // reduce traverses the array and we return the result
  return array.reduce(function(acc, b) {
     // if is an array we use recursion to perform the same operations over the array we found 
     // else we just concat the element to the accumulator
     return acc.concat( Array.isArray(b) ? flatten(b) : b);
  }, []); // we initialize the accumulator on an empty array to collect all the elements
}
 3
Author: alejandro,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-16 02:07:12

Polecam funkcję generatora :

function* flatten(arr) {
  if (!Array.isArray(arr)) yield arr;
  else for (let el of arr) yield* flatten(el);
}

// Example:
console.log(...flatten([1,[2,[3,[4]]]])); // 1 2 3 4

W razie potrzeby utwórz tablicę spłaszczonych wartości w następujący sposób:

let flattened = [...flatten([1,[2,[3,[4]]]])]; // [1, 2, 3, 4]
 3
Author: le_m,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-22 02:32:23