Home > Enterprise >  is there any other way to get a reduced array? because my array is not getting returned.I have no cl
is there any other way to get a reduced array? because my array is not getting returned.I have no cl

Time:04-14

i am trying to get a reduced array. my output is supposed to be like [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 );

  • Related