преобразование массивов

Есть массив arr = [["a"], ["b"], ["c"], ["d"], ["e"], ["f"]] .

Как преобразовать его в [["a", "b"], ["c", "d"], ["e", "f"]] ?


Ответы (3 шт):

Автор решения: Zhihar

ну можно просто в лоб

  arr = ["a", "b", "c", "d", "e", "f"]
  
  res = [[]];
  
  arr.forEach((obj, index) => {
    res[res.length - 1].push(obj);
    
    if ((index % 2 === 1) && (index < arr.length - 1))
        res.push([]);
  });

  console.log(res);

можно еще в лоб, но покороче

  arr = ["a", "b", "c", "d", "e", "f"]
  
  res = [];
  
  for (let index = 0; index < arr.length / 2; index ++)
    res.push(arr.slice(index * 2, index * 2 + 2));
  
  console.log(res);

можно покороче, но тоже в лоб

  arr = ["a", "b", "c", "d", "e", "f"]
  
  res = [];
  
  for (let index = 0; index < arr.length; index += 2)
    res.push([arr[index], arr[index + 1]]);
  
  console.log(res);

Тут возникло подозрение, а не имел ли автор в виду

arr = [["a"], ["b"], ["c"], ["d"], ["e"], ["f"]]

Тогда решение схожее, к примеру:

  arr = [["a"], ["b"], ["c"], ["d"], ["e"], ["f"]]

  res = []
  
  for (let index = 0; index < arr.length; index += 2)
    res.push([arr[index][0], arr[index + 1][0]]);
  
  console.log(res);

→ Ссылка
Автор решения: DiD

Решение немного нетривиальное

const arr = [["a"], ["b"], ["c"], ["d"], ["e"], ["f"], ["g"]];
console.log(arr.flat().filter((v,i)=>!(i%2)).map((v,i)=>[v,...(arr[2*i+1]||[,])]));
// => [ 0: ["a", "b"], 
//      1: ["c", "d"], 
//      2: ["e", "f"], 
//      3: ["g", undefined ] ]
→ Ссылка
Автор решения: Anthony V

В Lodash есть функция которая делает то что вам нужно https://lodash.com/docs/4.17.15#chunk

В этой библиотеке вы сможете найти множество готовых решений

_.chunk(['a', 'b', 'c', 'd', 'e', 'f'], 2);
// => [['a', 'b'], ['c', 'd'], ['e', 'f']]

_.chunk(['a', 'b', 'c', 'd', 'e', 'f'], 3);
// => [['a', 'b', 'c'], ['d', 'e', 'f']]
→ Ссылка