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"]
.
CodePudding user response:
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"))
CodePudding user response:
It is also possible like this
const arr = ["Apple", "Banana", "Cherry", "Orange", "Avocado", "Ananas", "Pineapple"];
const query = 'pp';
arr.filter(element => element.includes(query));
CodePudding user response:
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 ))
CodePudding user response:
<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>
CodePudding user response:
You can use Array.prototype.filter() combined with String.prototype.includes():
const result = arr.filter(el => el.toLowerCase().includes(input.toLowerCase()))
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.toLowerCase()))
console.log(`Result for ${input}:`, result)
})