How do I search through an array using a string, which is split into an array with JavaScript?


We are given an array of strings and another string for which we are required to search in the array. We can filter the array checking whether it contains all the characters that user provided through the input.

The code for doing the same would be −

Example

Solution 1

const deliveries = ["14/02/2020, 11:47,G12, Kalkaji", "13/02/2020, 11:48,
A59, Amar Colony"];
const input = "g12, kal";
const pn = input.split(" ");
const requiredDeliveries = deliveries.filter(delivery =>
pn.every(p =>
delivery.toLowerCase()
.includes(p.toLowerCase())));
console.log(requiredDeliveries);

Output

The output in console −

["14/02/2020, 11:47,G12, Kalkaji"]

In another and a bit better approach we can remove the step of splitting the input as shown below −

Example

Solution 2

const deliveries = ["14/02/2020, 11:47,G12, Kalkaji", "13/02/2020, 11:48,
A59, Amar Colony"];
const input = "g12, kal";
const requiredDeliveries = deliveries
.filter(delivery =>
delivery.toLowerCase()
.includes(input.toLowerCase()));
console.log(requiredDeliveries);

But while using this second approach, we have to keep in mind that it is sequence sensitive means AB will match with ab or Ab but not with BA or ba.

The output in console −

Output

["14/02/2020, 11:47,G12, Kalkaji"]

Updated on: 18-Aug-2020

139 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements