Learner
Learner

Reputation: 603

Filter array based on the keyword

I have an array:

let array = [
  'Hello 1» (Foo_Test-Editable)', 
  'Hello 2» (Foo_Test-Editable)', 
  'Hello 3»  (Foo_Test)', 
  'Foo_Test_4'
];

let searchKeyword = 'Foo_Test';
const result = array.filter(f => f.indexOf(searchKeyword) != -1);
console.log(result);

Rules to find:

Desired result is:

let result = [
    'Hello 3»  (Foo_Test)'
];

How to filter using the above rule?

Upvotes: 0

Views: 76

Answers (3)

Calebe Fazzani
Calebe Fazzani

Reputation: 71

If you can change the keyword to a regex...

let array = [
    'Hello 1» (Foo_Test-Editable)', 
    'Hello 2» (Foo_Test-Editable)', 
    'Hello 3»  (Foo_Test)', 
    'Foo_Test_4'
  ];
  
  let searchKeyword = /Foo_Test[^-|_]/;
  const result = array.filter(f => searchKeyword.test(f));
  console.log(result);

Upvotes: 3

Sudarshan Rai
Sudarshan Rai

Reputation: 306

Actually your code is working , output was 3 array because all of them contained search value Foo_Test

(3) ["Hello 1» (Foo_Test-Editable)", "Hello 2» (Foo_Test-Editable)", "Hello 3»  (Foo_Test)"]

so add parentheses around (Foo_Test) to distinguish it from other, which will output specific value

(Foo_Test)

Upvotes: 1

symlink
symlink

Reputation: 12208

Add the parentheses around "Foo_Test" to distinguish it.

let srch = "(Foo_Test)"

let arr = [
    "Hello 1» (Foo_Test-Editable)",
    "Hello 2» (Foo_Test-Editable)", 
    "Hello 3»  (Foo_Test)", 
    "FooText"
]

let srch = "(Foo_Test)"

const result = arr.filter( f => f.indexOf(srch)!= -1)

console.log(result)

Upvotes: 1

Related Questions