I have some code which is meant to do the following:
Given two arrays of strings
a1anda2return a sorted arrayrin lexicographical order of the strings ofa1which are substrings of strings ofa2.
Arrays are written in "general" notation.
Now I'm doing a test where array1 = ["arp", "live", "strong"] and array2 = ["lively", "alive", "harp", "sharp", "armstrong"].
I think I've got it, but I don't understand why the function only returns the array ["arp", "strong"] when in the last for loop I replace newArray.splice(l, l+1) with newArray.splice(k, k+1).
Could anyone tell me why that is?
function inArray(array1, array2) {
var newArray = [];
var sortedArray = [];
for (var i in array2) {
for (var j in array1) {
if (array2[i].includes(array1[j])) {
newArray.push(array1[j]);
};
};
};
sortedArray = newArray.sort();
for (var k = 0; k < newArray.length; k++) {
for (var l = 0; l < newArray.length; l++) {
if (newArray[k] === newArray[l] && k != l) {
newArray.splice(l, l + 1)
}
}
}
return sortedArray;
};
console.log(inArray(["arp", "live", "strong"], ["lively", "alive", "harp", "sharp", "armstrong"]));
Looks like you're overcomplicating it a bit ;)