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.
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.
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.
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.
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.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With