Kayra
Kayra

Reputation: 83

Javascript: Filter elements parts in Array

I am trying to select all the elements in an Array that contain the word "Orange", independently of the number before.

I tried with this code, but it is only working when I write the exact element name like "02orange".

var DWArray = ["apple", "apple", "02orange", "03orange", "04orange", "potato"];

function checkOrange(orange) {
    return orange == "02orange";
}
var OrangeArray = DWArray.filter(checkOrange);
return OrangeArray.join(", ");

My desired result is:

["02orange", "03orange", "04orange"];

Upvotes: 2

Views: 115

Answers (4)

jo_va
jo_va

Reputation: 13983

You can do it with a regex and RegExp.test() in one line:

const DWArray = ["apple", "apple", "02orange", "03orange", "04orange", "potato"];
const OrangeArray = DWArray.filter(s => /orange/i.test(s)).join(', ');

console.log(OrangeArray);

Upvotes: 0

guest271314
guest271314

Reputation: 1

One option would be to use RegExp constructor and RegExp.prototype.test() with string "orange" passed as first parameter and i (ignore case; if u flag is also enabled, use Unicode case folding) and g flags (global match; find all matches rather than stopping after the first match) passed as second parameter

var DWArray = ["apple", "apple", "02orange", "03orange", "04orange", "potato"];

function checkOrange(orange) {
  return new RegExp("orange", "ig").test(orange)
}

var OrangeArray = DWArray.filter(checkOrange);

console.log(OrangeArray, OrangeArray.join(", "));

Upvotes: 2

Nina Scholz
Nina Scholz

Reputation: 386848

You could return the result of the check with String#includes.

function checkOrange(orange) {
    return orange.includes("orange");
}

var DWArray = ["apple", "apple", "02orange", "03orange", "04orange", "potato"],
    OrangeArray = DWArray.filter(checkOrange);

console.log(OrangeArray.join(", "));

For older Browser, you might use String#indexOf.

function checkOrange(orange) {
    return orange.indexOf("orange") !== -1;
}

var DWArray = ["apple", "apple", "02orange", "03orange", "04orange", "potato"],
    OrangeArray = DWArray.filter(checkOrange);

console.log(OrangeArray.join(", "));

Upvotes: 2

ellipsis
ellipsis

Reputation: 12152

Use .includes to check if the string includes orange in it, with filter. Refer

var DWArray = ["apple", "apple", "02orange", "03orange", "04orange", "potato"];
console.log(DWArray.filter(e=>e.includes('orange')))

Upvotes: 0

Related Questions