Reputation: 25
I would like to compare two lists with Javascript. I want to output everything from WORDLIST that contains END. (should not be in the middle of the word, but the last characters)
jQuery would also work for me.
var WORDLIST = ['instagrampost', 'facebookpost', 'google']
var END = ['post', 'gle']
function compare() {
var final = WORDLIST.endsWith(END, END.length);
console.log(final);
}
// count the signs of end
// take wordlist and take end.lenght from behind
// save a word from the wordlist as result, if it contains a word from end as result
Upvotes: 2
Views: 566
Reputation: 3549
Here a solution without regex, base on indexOf
:
var WORDLIST = ['instagrampost', 'facele', 'facebookpost', 'google', 'dnuiwa']
var END = ['post', 'gle']
function endsWith(wordlist, end){
return wordlist.filter((w) =>
end.filter((e) => w.indexOf(e) == w.length - e.length).length > 0
);
}
console.log(endsWith(WORDLIST, END))
Upvotes: 1
Reputation: 15530
You may Array.prototype.filter()
your WORDLIST
based on whether Array.prototype.some()
item of END
is an ending (String.prototype.endsWith()
) of a word:
const WORDLIST = ['instagrampost', 'facebookposting', 'google'],
END = ['post', 'gle'],
result = WORDLIST.filter(w =>
END.some(e => w.endsWith(e)))
console.log(result)
p.s. if you need case-insensitive match, you may do w.toLowerCase().endsWith(e.toLowerCase())
Upvotes: 4