Julien Duv
Julien Duv

Reputation: 13

nested functions returning undefined

hi I want to get the result of this function at once inside the items variable, but when I try to return items I get undefined value , can someone explain why and fix it please?

let arr= [[1,2,3,4],[5,6,7,8],['a','b','c','d']];
let colp = [0,1,3];

 function selCol(arr,colp) {
     let items = [];
    return colp.forEach((element) => {
      return  arr.map((row) => {

      items.push(row[element]);

      return items;

      });
       
    });

  }

Upvotes: 0

Views: 323

Answers (2)

Souki1990
Souki1990

Reputation: 151

Maybe you can return items, and in that case map is not necessary

function selCol(arr, colp) {
    let items = [];
    colp.forEach((element) => {
        arr.forEach((row) => {
            items.push(row[element]);
            return items;
        });

    });
    return items;
}

Upvotes: 1

can_pacis
can_pacis

Reputation: 315

It is about the 'forEach'. forEach method returns undefined, if you want to return a value either map it or if you want to items in its mutated version, return it directly as such;

function selCol(arr, colp) {
  let items = [];
  colp.forEach((element) => {
    return arr.map((row) => {
      items.push(row[element]);

      return items;
    });
  });
  return items;
}

Upvotes: 0

Related Questions