The Output should be only: rabbit and bibe but im getting it wrong all in the list is printing because last index has ‘b’ as well how can i print the specified element that contain only ‘bib’
let str = 'bib'
let list = ['rabbit', 'bibe', 'bundle']
for (let i = 0; i < list.length; i++) {
for (let j = 0; j < list[i].length; j++) {
let foundIndex = str.indexOf(list[i][j]) > -1
if (foundIndex === -1) {
list.splice(foundIndex, 1)
} else if (foundIndex) {
console.log(list[i])
}
}
}
Expecting Output should be:
rabbit
bibe
3
Answers
A simple solution would be counting the number of each unique character in the given string and then filter the elements base on that: If an element has all of those characters, each with the same or higher amount, then it should be kept.
First, declare a helper function:
It will return an object that looks like this:
Array
objects have a very convenient method named.every()
which returnstrue
if and only if the callback function returns true for all elements. We want to make use of it, so we convert the object above to an array of key-value pairs usingObject.entries()
:We do the same for each element of the list (not the
Object.entries()
part; we don’t need their.every()
):This is the tricky part: For every word in the list, we check if it contains every character in the given string, each with the same or higher amount. If it does,
.every()
will returntrue
and.filter()
will keep the word in the new list:Try it:
You can simply achieve this with the help of
Array.every()
method which tests whether all elements in the array pass the test implemented by the provided function. It returns aBoolean
value.Live Demo :
Updated answer as per the author comment :
Here’s another solution, if we sort the letters "bib" becomes "bbi".
If we do a similar thing with the list ["rabbit","bibe","bundle"] becomes ["abbirt", "bbei" and "bdelnu"]. If we filter the letters not in "bib" the list shrinks to ["bbi","bbi","b"]. What we can now do is check for the occurrences of "bbi" in the resultant list.
Here’s an intermediate implementation of the above:
Here’s the same code but golfed some more: