Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
833 views
in Technique[技术] by (71.8m points)

arrays - Javascript filter check for multiple values?

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 }
];
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...