0

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;

      });
       
    });

  }

1
  • 1
    forEach() doesn't return anything. map() does. So return colp.forEach((element) => { will always return nothing. Commented May 19, 2020 at 18:11

2 Answers 2

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

0

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.