Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array traversal in JavaScript to fill two maps

var numerList = [1, 3, 7, 2, 4, 16, 22, 23];
var evenNoLst = numerList.map(function(no) {
  return ((no % 2) === 0);
});
console.log(evenNoLst)

Above code for me is creating a map of even numbers, now I also want to have odd number list. Do I need to traverse through number list again? or is there a way to have two maps using single traversal of an array.

I am using Javascript.

like image 236
user987316 Avatar asked Feb 26 '18 07:02

user987316


People also ask

Can you map two arrays in JavaScript?

Approach: For this, we can create two arrays, in which one array contains the array elements that are to be mapped, and the second array stores all the return values of the corresponding function. We can use the JavaScript Array push() method to push the return values of the function in the output array.

How do you map an array in JavaScript?

The syntax for the map() method is as follows: arr. map(function(element, index, array){ }, this); The callback function() is called on each array element, and the map() method always passes the current element , the index of the current element, and the whole array object to it.

Can we create a array of maps?

C++ allows us a facility to create an array of maps. An array of maps is an array in which each element is a map on its own.


2 Answers

Here's a way to split it in one go with reduce:

var numberList = [1, 3, 7, 2, 4, 16, 22, 23];

var grouped = numberList.reduce(function (acc, x){  
  acc[x%2].push(x);
  return acc;
}, [[], []]);

console.log(grouped);

The result is an array with two arrays inside: the first one has the even numbers and the second one the odd ones.

like image 94
Cristian Lupascu Avatar answered Oct 10 '22 18:10

Cristian Lupascu


You could take the logical NOT operator and map all boolean values.

var numerList = [1, 3, 7, 2, 4, 16, 22, 23],
    evenNoLst = numerList.map(no => no % 2 === 0),
    oddNoLst = evenNoLst.map(b => !b);

console.log(evenNoLst);
console.log(oddNoLst);
.as-console-wrapper { max-height: 100% !important; top: 0; }

With a single loop approach

var numerList = [1, 3, 7, 2, 4, 16, 22, 23],
    oddNoLst = [],
    evenNoLst = [];

numerList.forEach(function (no) {
    var even = no % 2 === 0;
    evenNoLst.push(even);
    oddNoLst.push(!even);
});

console.log(evenNoLst);
console.log(oddNoLst);
.as-console-wrapper { max-height: 100% !important; top: 0; }

With for ... of loop

var numerList = [1, 3, 7, 2, 4, 16, 22, 23],
    oddNoLst = [],
    evenNoLst = [],
    no, even;

for (no of numerList) {
    even = no % 2 === 0;
    evenNoLst.push(even);
    oddNoLst.push(!even);
}

console.log(evenNoLst);
console.log(oddNoLst);
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 36
Nina Scholz Avatar answered Oct 10 '22 20:10

Nina Scholz