I am comparing two arrays with each other in a function and want to return an array with the highest values at each array key. In my function I have two parameters which both represent an array.
The arrays have the same length and their key values are normal index numbers
Now I just use a normal for loop:
var array1 = [50, 30, 44, 8];
var array2 = [12, 44, 18, 9];
function createList(arr1, arr2){
for(var x = 0; x < arr1.length; x++){
arr1[x] = arr1[x] > arr2[x]?arr1[x]:arr2[x];
}
return arr1;
}
var highList = createList(array1, array2);
Now I know there are other possiblities of getting this result. But what I was wondering whether you can get the current key in the map method and use that to compare it with another array.
Something in the line of:
var highList = array1.map(function(num){
return num > array2[keyOfCurrentMap]?num:array2[keyofCurrentMap];
});
var highList = array1.map(function(num, keyOfCurrentMap){
return num > array2[keyOfCurrentMap]?num:array2[keyofCurrentMap];
});
The second param passed into the callback for map
is the key.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.