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.

Using Array Filter with Split (Flexible Search)

This approach splits the search string into parts and checks if each part exists in the array elements, regardless of order.

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);
["14/02/2020, 11:47,G12, Kalkaji"]

Using Direct String Match (Sequential Search)

This simpler approach searches for the entire input string as a continuous sequence within each array element.

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);
["14/02/2020, 11:47,G12, Kalkaji"]

Key Differences

The second approach is sequence-sensitive, meaning "g12, kal" will match but "kal, g12" won't match the same string. The first method is more flexible as it checks each part independently.

Enhanced Example with Multiple Matches

const products = [
    "Apple iPhone 12 Pro Max 256GB",
    "Samsung Galaxy S21 Ultra 128GB", 
    "Apple MacBook Pro M1 256GB",
    "Dell XPS 13 Intel i7 512GB"
];

const searchTerms = "apple 256";
const parts = searchTerms.split(" ");

console.log("Flexible search results:");
const flexibleResults = products.filter(product =>
    parts.every(part =>
        product.toLowerCase().includes(part.toLowerCase())));
console.log(flexibleResults);

console.log("\nSequential search results:");
const sequentialResults = products.filter(product =>
    product.toLowerCase().includes(searchTerms.toLowerCase()));
console.log(sequentialResults);
Flexible search results:
["Apple iPhone 12 Pro Max 256GB", "Apple MacBook Pro M1 256GB"]

Sequential search results:
[]

Conclusion

Use the split-based approach for flexible multi-term searching where order doesn't matter. Use direct string matching when you need exact sequence matching within array elements.

Updated on: 2026-03-15T23:18:59+05:30

276 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements