Okay, so this is something i partially have working (ignoring case sensitivity) comparing the following:
arrayA = [\"apples\", \"Oranges\", \"salt\", \"Crack
Since arrayB
contains the "needles", and arrayA
contains the "haystacks", so to speak, you can use String.prototype.includes(). Note you are actually using Array.prototype.includes() in your attempt, which is why it only matches "salt"
(based on your example code, I am highly doubtful that even "orange"
was a successful match).
Below is a solution that uses String.prototype.includes()
instead:
function matchedSubstrings (haystacks, needles) {
return needles.filter(function (needle) {
const lowerCaseNeedle = needle.toLowerCase()
return this.some(haystack => haystack.includes(lowerCaseNeedle))
}, haystacks.map(haystack => haystack.toLowerCase()))
}
const arrayA = ["apples", "Oranges", "salt", "Cracked Black Pepper"]
const arrayB = ["Salt", "pepper", "orange"]
console.log(matchedSubstrings(arrayA, arrayB))
The this
of the Array.prototype.filter() callback function is the transformed haystacks
array passed as the second argument.
The equivalent TypeScript is as follows:
function matchedSubstrings (haystacks: string[], needles: string[]): string[] {
return needles.filter(function (this: string[], needle) {
const lowerCaseNeedle = needle.toLowerCase()
return this.some(haystack => haystack.includes(lowerCaseNeedle))
}, haystacks.map(haystack => haystack.toLowerCase()))
}
const arrayA = ["apples", "Oranges", "salt", "Cracked Black Pepper"]
const arrayB = ["Salt", "pepper", "orange"]
console.log(matchedSubstrings(arrayA, arrayB))