I have a problem applying to return an array after applying a condition.
Here it is,
With a given array: [1, 2, 3]
Condition 1: If it is an Odd, should multiply *2.
Condition 2: If it is an Even, just return it.
Expected_Result: [2, 2, 6]
Here is my approach;
function oddToEven(array) {
var evens = [array];
var odds = [array];
if (array %2 !== 0){
array *2;
return odds;
} else {
return evens;
}
}
oddToEven(1,2,3); // returns => [1]
I know this is pretty basic, and surely my approach is all wrong, but this is my very first week learning JS, I hope some of you give me a light on this!
Thanks a lot
Use
.map
to transform one array into another - what is returned from each call of the callback function will be the item in the same index in the new array:Or, to be more verbose:
Of course, this assumes that every item in the original array is an integer.
If you want to pass the array in a function :-
When doing
[array]
you basically wrap the array into another array, you probably don't need[[1, 2, 3]]
. To copy an array, use[...array]
, however, do you really need three arrays? Wouldn't it be enough to go over the passed array, and change it according to the rules? For that we have to go over the indices of the array:Now inside that loop, you can get the current element with
array[i]
, and also modify it witharray[i] = ?
... You can also check if it is even withYou can use a simple
forEach()
loop for that:In JavaScript we usually use
map
,filter
andreduce
to solve this kind of problem in a functional wayNote that map will crate a new array so your original array will remain the same. Usage:
This is how you can modify your own code: