user1751287
user1751287

Reputation: 501

compare element position from first array with number from second one

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                     
   }
}

Upvotes: 0

Views: 338

Answers (3)

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48407

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

Upvotes: 2

Hackerman
Hackerman

Reputation: 12295

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/

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337627

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

Upvotes: 1

Related Questions