Skip to content Skip to sidebar Skip to footer

JavaScript Compare Arrays

I have an array in the following format: var markers = [ ['Title', 15.102253, 38.0505243, 'Description', 1], ['Another Title', 15.102253, 38.0505243, 'Another Description'

Solution 1:

One option is to use nested loops:

var markers = [
    ['Title', 15.102253, 38.0505243, 'Description', 1], 
    ['Another Title', 15.102253, 38.0505243, 'Another Description', 2],
    ['Title 3', 15.102253, 38.0505243, 'Description 3', 3], 
];
var search = ['1', '2'];
var result = [];

for (var i = 0; i < search.length; i++)
    for (var j = 0; j < markers.length; j++)
        if (search[i] == markers[j][4]) {
            result.push(markers[j]);
            break;
        }

console.log(result);

DEMO: http://jsfiddle.net/3TErD/


Solution 2:

Couldn't you just use a nested loop here?

var filteredMarkers = [];

for(var i = 0; i < markers.length; i++) {

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

        // this might need to be changed as your markers has index 4 as a number whereas the queryString array appears to be strings.
        if(markers[i][4] === queryStringArray[j]) {

            filteredMarkers.push(markers[i]);
            break;

        }

    }

}

Post a Comment for "JavaScript Compare Arrays"