Ann
Ann

Reputation: 139

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.

Upvotes: 0

Views: 38

Answers (2)

SoumyaMurthy
SoumyaMurthy

Reputation: 11

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.

Upvotes: 0

jcubic
jcubic

Reputation: 66660

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 
    }
}

Upvotes: 3

Related Questions