Home > Software design >  How to get a reduced array? My array is not getting returned
How to get a reduced array? My array is not getting returned

Time:04-14

I am trying to get a reduced array.

My output is supposed to be [1,5,4] but it gives me an empty array.

let arr=[1,[2,3],4]
let newarr=[]
 
let myarr=()=>{
    for(i=0;i<3;i  ){
        array=arr[i].reduce
        newarr.push(array)
        return newarr
    }
}

CodePudding user response:

You need to pass a function to your array.reduce,also you have to actually call your function,like so ( console.log calls it ):

const arr = [1, [2, 3], 4];

const myArr = (arr) => {
  let newArray = [];
  arr.forEach((arrayItem) => {
    //we iterate every item in given array
    if (Array.isArray(arrayItem)) {
      //we check if item is actually an array to reduce
      newArray.push(
        arrayItem.reduce(function (previous, current) {
          return previous   current;
        })
      ); //if its an array then reduce it down to a single value using a reducer function and push it in new array
    } else {
      newArray.push(arrayItem); //otherwise just push it in new array as is
    }
  });
  return newArray;
};

console.log( myArr(arr) );

there are always shorter and prettier ways to do the same,above solution is as readable as possible to understand it,an one-liner would be :

const arr = [1, [2, 3], 4]
const newArr = arr.map(i=>Array.isArray(i)?i.reduce((a,b)=>a b):i)
console.log(newArr)

CodePudding user response:

Array#reduce is an array method and it needs a function to be passed to it. Also you have defined a function but you do not invoke it.

Try the following:

let arr = [1, [2, 3], 4];
let newarr = [];
 
((array) => {
    for(let i=0; i < array.length; i  ) {
        const el = array[i];
        const topush = Array.isArray(el) ? el.reduce((total, curr) => total   curr, 0) : el;
        newarr.push(topush)
    }
})( arr );

console.log( newarr );

Alternatively, you can use Array#map and Array#reduce methods as follows. In both cases the trick is to identify the array so as to apply reduce to it:

const arr = [1, [2, 3], 4, [4, 5, 7]];

const newarr = arr.map(el => 
    Array.isArray(el) ? el.reduce((sum,cur) => sum   cur,0) : el
);

console.log( newarr );

  • Related