0

In my code below, I created a fn callback function to return values < 2, after the loop in the map function runs through the array passed as the parameter. But the console is logging an array of booleans instead of values

What am I doing wrong?

 var newarr = []

function fn(val){
  return val < 3;
}

function map(arr){
  for (var i = 0; i < arr.length; i++){
    newarr.push(fn(arr[i]));
  }
  console.log(newarr);
}

map ([1,2,3,4,5,6], fn);

My Result

[ true, true, false, false, false, false ]
1
  • val < 3 is a condition check and will return Boolean Commented Aug 29, 2017 at 9:17

4 Answers 4

1

It's because result of fn is boolean:

return val < 3; // true or false

If you need to filter elements, then the logic should be a little bit different, and the name should be filter, not map:

var newarr = [];

function fn(val) {
  return val < 3;
}

function filter(arr) {
  for (var i = 0; i < arr.length; i++) {
    if (fn(arr[i])) {
      newarr.push(arr[i]);
    }
  }
  console.log(newarr);
}

Also ES6 natively supports Array#filter function:

let newArray = arr.filter(item => item < 3);
Sign up to request clarification or add additional context in comments.

Comments

0

You should use Array.prototype.filter with your callback for your purpose.

Comments

0

correction in your code:

var newarr = []

function fn(val){
  return val < 3;
}

function map(arr){
  for (var i = 0; i < arr.length; i++){
if(fn(arr[i]))
      newarr.push(arr[i]);
  }
  console.log(newarr);
}

map ([1,2,3,4,5,6], fn);

and ES6 code for the same solution

var newarr = [1,2,3,4,5,6].filter(function(item){
return item<3;
})
console.log(newarr);

Comments

0

Read this - Array.prototype.filter

var arr = [1,2,3,4,5,6];
var newArr = arr.filter((val) => val < 3); // [1,2]

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.