0

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', 2],
    ['Title 3', 15.102253, 38.0505243, 'Description 3', 3], 
];

I then have a query string being passed to the page (m=1,2), which being comma separated, is then split to create an array like the following:

['1', '2']

What I need to do is find all 'markers' where the ID (markers[i][4]) comes from the query string.

What would be the best way to achieve this? Ideally I want to create a 3rd array in the same format as 'markers' but only showing the results from the query string.

Any help would be greatly appreciated.

Thanks

0

2 Answers 2

2

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/

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

2 Comments

Snap! +1 for describing the setup steps too!
Awesome - thanks for this. So many variations but this one takes my pick. Thanks for the demo link too :)
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;

        }

    }

}

4 Comments

Just add Number( queryStringArray[ j ] )
Yeah there are many ways to resolve that potential issue, the question is around the logic of matching values between two arrays though, so as a solution for that it's ok I guess!
For author's arrays your variant will go one cycle more than mine ;)
Very true, I thought about that afterwards! depends on the two arrays of course but from the descriptions yours would be more efficient :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.