0

I am trying to compare the two arrays, more specifically to do something with values from the first one whose positions matches the numbers from second one.

var valuesList = ['value1', 'value2', 'value3', 'value4', 'value5'],
    positionNumberList = [0, 2, 4];

from above arrays value1 should be eq to 0 from second one, value3 = 2 .etc

I started with the code below but can not get the position of the values from the first array.

for(j=0; j < valuesList.length; j++){

   for(k=0; k < positionNumberList.length; k++){
       //find matching values from first array                     
   }
}
1
  • 2
    What is the final array you want? Commented Feb 9, 2017 at 14:05

3 Answers 3

2

One of the solutions is use map() method which applies a provided callback function for every item from array.

var valuesList = ['value1', 'value2', 'value3', 'value4', 'value5'],
 positionNumberList = [0, 2, 4];

console.log(positionNumberList.map(function(item) {
  return valuesList[item];
}));

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

Comments

1

To do this you only need a single loop to iterate through the positionNumberList array, and then access the items in valuesList with the given indexes, like this:

var valuesList = ['value1', 'value2', 'value3', 'value4', 'value5'];
var positionNumberList = [0, 2, 4];

positionNumberList.forEach(function(index) {
  var value = valuesList[index];

  console.log(value);
});

Comments

0

Another approach:

var valuesList = ['value1', 'value2', 'value3', 'value4', 'value5'],
    positionNumberList = [0, 2, 4];


if(positionNumberList.length < valuesList.length){
     for(var i=0; i < positionNumberList.length; i++){
         console.log(positionNumberList[i],valuesList[i])
     }
}
else{
    for(var i=0; i < valuesList.length; i++){
         console.log(valuesList[i],positionNumberList[i])
     }
}

https://jsfiddle.net/xrjjxmbn/

Comments

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.