I'm trying to remove items from array that are present already in longer items. For Example if I have two items 'Knowledge base' and 'base' I want to remove 'base', if I have knowledge management multiple times I want to leave all items unless there is an item that contain those two words but it's longer for example 'knowledge management book'.
It's easy to sort items by length but I'm not sure how to check for example if 'base' is already present in longer term('Knowledge base')
So in the example below desired solution would be:
const items = ['Knowledge base', 'knowledge management', 'knowledge management']
const items = ['Knowledge base', 'base', 'management', 'knowledge management', 'Knowledge', 'knowledge', 'knowledge management']
const newItems = items.sort((a,b) => b.length - a.length)
console.log(newItems)
CodePudding user response:
You can use Array.filter()
along with Array.some()
to filter any items that are included in other items.
const items = ['Knowledge base', 'base', 'management', 'knowledge management', 'Knowledge', 'knowledge', 'knowledge management'];
const result = items.filter(item => !items.some(it => it !== item && it.includes(item)));
console.log('Result:', result);
CodePudding user response:
Filter by some and verify by includes methods
const items = ['Knowledge base', 'base', 'management', 'knowledge management', 'Knowledge', 'knowledge', 'knowledge management'];
const newItems = items.filter((item) => {
return !items.some((iChecker) => {
return iChecker !== item && iChecker.includes(item)
}
)
}
);
console.log( { newItems } );