简体   繁体   中英

How to select elements from this array

I have two arrays. If arrayTwo has color "blue and "red" then return "blue painting", "red sofa", "blue pot" from arrayOne.

var arrayOne = ["green wall", "blue painting", "red sofa", "yellow shelf", "blue pot"];

var arrayTwo = ["blue", "red"];

for (var i=0; i < arrayOne.length; i++ ) {
if (arrayOne[i] == "blue" || "red"){
// this should give colors that match in arrayOne 
 }
}

edit: I want to know if the words match in array one and two. But not hardcoding it.

You can use regular expressions for that:

var arrayOne = ["green wall", "blue painting", "red sofa", "yellow shelf", "blue pot"];

var arrayTwo = ["blue", "red"];
var regex = new RegExp('^(' + arrayTwo.join('|') + ')');
for (var i=0; i < arrayOne.length; i++ ) {
    if (arrayOne[i].match(regex)) {
       // this should give colors that match in arrayOne 
    }
}

As a basic algorithm, you could loop over each element in the first array , split it using the String.prototype.split method and compare the first word with the elements in second array. if it matches, you can print the element at that index.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM