'Search Array of strings for matching character sequence
I have an array like this
const arr = ["Apple", "Banana", "Cherry", "Orange", "Avocado", "Ananas", "Pineapple];
I need a function that returns an array with all the Elements from arr, that match the given character sequence. The order of the characters is of importance.
Given "ppl" the function should return ["Apple", "Pineapple"].
Given "n" the function should return ["Banana", "Orange", "Ananas", "Pineapple"].
Given "voca" the function shoould return ["Avocado"]
Given "rr" the function should return ["Cherry"], while given a "r" the function should return ["Cherry", "Orange"].
Solution 1:[1]
try this
const arr = ["Apple", "Banana", "Cherry", "Orange", "Avocado", "Ananas", "Pineapple"];
const search = query => arr.filter(s => s.toLowerCase().includes(query))
console.log(search("n"))
console.log(search("ppl"))
Solution 2:[2]
It is also possible like this
const arr = ["Apple", "Banana", "Cherry", "Orange", "Avocado", "Ananas", "Pineapple"];
const query = 'pp';
arr.filter(element => element.includes(query));
Solution 3:[3]
It's pretty straight forward using filter function and indexOf
const arr = ["Apple", "Banana", "Cherry", "Orange", "Avocado", "Ananas", "Pineapple"];
const cond = 'ppl'
console.log(arr.filter(x => x.indexOf(cond) > -1 ))
Solution 4:[4]
<script>
function checkPattern(str, pattern) {
var len = pattern.length;
if (str.length < len) {
return false;
}
for (var i = 0; i < len - 1; i++) {
var x = pattern[i];
var y = pattern[i + 1];
var last = str.lastIndexOf(x);
var first = str.indexOf(y);
if (last === -1 || first === -1 || last > first) {
return false;
}
}
return true;
}
var str = "engineers rock";
var pattern = "gin";
document.write(checkPattern(str, pattern));
</script>
Solution 5:[5]
You can use Array.prototype.filter() combined with String.prototype.includes():
const result = arr.filter(el => el.toLowerCase().includes(input))
Code:
const arr = ["Apple", "Banana", "Cherry", "Orange", "Avocado", "Ananas", "Pineapple"]
const inputs = ["ppl", "n", "voca", "rr", "r"]
inputs.forEach(input => {
const result = arr.filter(el => el.toLowerCase().includes(input))
console.log(`Result for ${input}:`, result)
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | R4ncid |
| Solution 2 | Stophface |
| Solution 3 | Stefan Avramovic |
| Solution 4 | Ansh Chandarana |
| Solution 5 |
