0

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.

3
  • Maybe explain your problem and what you are trying to do. Are we talking about prefixes of the elements in arrayOne? Commented Nov 30, 2015 at 17:26
  • Is the desired output an array of elements in arrayOne that have prefixes found in arrayTwo? Commented Nov 30, 2015 at 17:31
  • The words can be in any order" Blue painting" or "true blue" Commented Nov 30, 2015 at 17:32

2 Answers 2

3

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 
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. I don't want to hardcode .match(/^(blue|red)/).
Not just prefix. Word can be matched like "blue wall" or "true blue"
@Ann just remove ^ from regex.
0

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.

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.