ogbeh
ogbeh

Reputation: 63

Javascript: for-loop returning array of booleans instead of array of values

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 ]

Upvotes: 0

Views: 63

Answers (4)

Kol007
Kol007

Reputation: 292

Read this - Array.prototype.filter

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

Upvotes: 0

alexmac
alexmac

Reputation: 19627

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

Upvotes: 1

Nemani
Nemani

Reputation: 784

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

Upvotes: 0

y_vyshnevska
y_vyshnevska

Reputation: 166

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

Upvotes: 0

Related Questions