65535
65535

Reputation: 553

Javascript: How to use the reduce function and the concat array function to transform an array of arrays into an array?

Javascript: How to use the reduce function and the concat array function to transform an array of arrays into an array?

In the following code, the array of arrays is not transformed and the browser console log logs an empty array.

Under the code below, what is the exact reason for the failure?

Any help would be greatly appreciated.

  // use reduce to transform an array of 
  // arrays to one array that combines all.
  // elements.

  function combine(array1d, element)
  {
    array1d.concat(element);

    return array1d;
  }

  function reduce(array2d, combine) {

    let array1d = [];

    for (let element of array2d) {

      array1d = combine(array1d, element);

    }

    return array1d;
  }

  let array2d =  [[1, 2,],[3, 4]];
  console.log(reduce(array2d, combine));

Upvotes: 1

Views: 6583

Answers (5)

Narigo
Narigo

Reputation: 3101

As you can see by all the answers, there are multiple ways to do this.

  1. One solution which is fixing the error in the original question:
function combine(array1d, element) {
  return array1d.concat(element);
}

function reduce(array2d, reducerFn) {
  let array1d = [];

  for (let element of array2d) {
    array1d = reducerFn(array1d, element);
  }

  return array1d;
}

let array2d =  [[1, 2,],[3, 4]];
console.log(reduce(array2d, combine));

The difference here is the return array1d.concat(element); call instead of returning array1d and call .concat on it. concat is side-effect free, so it creates a new array instead of mutating the original one. I've also renamed combine in reduce to reducerFn to make it more clear that it could be changed to something else.

  1. Using reduce directly on the array (supported by almost all browsers)
let result = array2d.reduce(function (flattenedArray, element) {
  return flattenedArray.concat(element);
}, []);
  1. Using reduce and the spread operator instead of concat (no IE support - if you can drop it, you can also use Arrow functions):
let result = array2d.reduce(function (flattenedArray, element) {
  return [...flattenedArray, ...element];
}, []);
  1. Using flatMap, the identity function can be used to flatten the array:
let result = array2d.flatMap(element => element);
  1. Using flat, which flattens (deeply) nested arrays the amount of dimensions it receives as an argument:
let result = array2d.flat();
  1. Using imperative style by creating a for loop for each dimension, fill the array in order - see answer by

flatMap and reduce, like concat, also return a new array, without mutating the original one. Since the original version looked more like trying to use a functional programming style to me, I guess these are a good addition to your toolbox. flatMap and flat are relatively recent additions to the language, so depending on the environments you need to support, you might end up using something else instead.

Upvotes: 1

Specy
Specy

Reputation: 331

Why don't you do it the old fashioned way?

function mergeArray(array){
    let finalArray= []
    for(let i=0;i<iarray.lenght;i++){
          for(let j=0;j<array[i].lenght;j++){
                 finalArray.push(array[i][j])
          }
    }
    return finalArray
}

Upvotes: 0

Dev Yego
Dev Yego

Reputation: 553

const res = array2d.reduce((arr, seq) => {
  arr.push(...seq);
  return arr;
}, [])
console.log(res)

Upvotes: 1

Giovanni Esposito
Giovanni Esposito

Reputation: 11156

Ciao, here working example:

let array2d =  [[1, 2,],[3, 4]];
let result = array2d.flat(1);
console.log(result);

Upvotes: 1

focus1691
focus1691

Reputation: 351

You can transform the 2D array into an array first with flat, and then use the reduce function to add the elements.

If you don't need to add the elements, just remove the reduce.

var res = array2d.flat().reduce((prev, curr) => prev + curr);

Upvotes: 1

Related Questions