0

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

1 Answer 1

2
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.

Sign up to request clarification or add additional context in comments.

2 Comments

Works as a charm, thanks for clearing this out for me.
Done! I had to wait for 15 minutes to pass after I posted my question before I was able to accept it. Thanks again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.