9

I am wondering how I can return multiple values from an array like this:

var countries = [
    { key: "Spain", doc_count: 1378 },
    { key: "Greece", doc_count: 1259 }
];

This is what I have set up so far and it works fine for returning a single value. I am wondering how I could pass an array of countries though instead of looking for a single country.

var countriesFound = countries.filter(function(country) {
    return country.key === 'Spain';
});

On that note I would also like to add the found object to the front of the array so I could have a copy of it inside my countries array.

Using this results in some unexpected results because I end up with an array as my first item in the countries array and my object that I want is stored withint that array.

countries.unshift(countriesFound);

Results in (at least I think it looks like this typed out):

var countries = [
    [{ key: "Spain", doc_count: 1378 }],
    { key: "Spain", doc_count: 1378 },
    { key: "Greece", doc_count: 1259 }
];

2 Answers 2

16

Change your filter to :

var countriesFound = countries.filter(function(country) {
    return ["Spain","Greece"].indexOf(country.key) != -1
});

Where ["Spain","Greece"] is your list of valid countries that you want to filter by. The value returned form the filter function applied to the array determines whether the element is filtered in or out. indexOf finds the position in the given array of the give country.key

As per the add the filtered array to the beginning of the other one you are correct, doing countries.unshift(countriesFound) after the previous code will achieve that.

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

2 Comments

Yeah I need something else though because it's adding the array of found countries as my first item but I actually just need to put them inside my array as single objects so they look like the other items in my array. The filter works though, thanks for helping out.
If you add them as single objects, they'll be duplicated (adding them to the original array). However, to achieve this you need concat. Like in filteredFirstThenRest = countriesFound.concat(countries)
9

The same answer as @Juan Corés, but with arrow function expression:

const countriesFound = countries.filter(country => 
    ["Spain","Greece"].indexOf(country.key) != -1
);

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.