Why does my function return a different array?

145 views Asked by At

I have some code which is meant to do the following:

Given two arrays of strings a1 and a2 return a sorted array r in lexicographical order of the strings of a1 which are substrings of strings of a2.
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"]));

3

There are 3 answers

0
georg On BEST ANSWER

Looks like you're overcomplicating it a bit ;)

a1 = ["arp", "live", "strong", "bazooka"]
a2 = ["lively", "alive", "harp", "sharp", "armstrong"]


result = a1
    .filter(x => a2.some(y => y.includes(x)))
    .sort();

console.log(result);

0
Barmar On

The reason is that the second argument to splice() isn't the end position of the splice, but the count of elements that should be removed. So when k = 1, you removed 2 elements, not just the element at index 1.

Both newArray.splice(l, 1) and newArray.splice(k, 1) work correctly.

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(k, 1);

    }
   }
  }
  return sortedArray;
};

console.log(inArray(["arp", "live", "strong"], ["lively", "alive", "harp", "sharp", "armstrong"]));

0
AudioBubble On

In the comments already you get the answer. Use ES2015/ES6 always you can, benefit of it's adventages.

const words1 = ["arp", "live", "strong"];
const words2 = ["lively", "alive", "harp", "sharp", "armstrong"];
const final = [];

words1.forEach(v => {
  words2.forEach(v2 => {
    if (v2.includes(v)) {
      final.push(v);
    }
  });
});

const finalSorted = [...new Set(final.sort())];

// just to add html
const pre = document.getElementById('result');

finalSorted.forEach(v => {
  let content = pre.textContent;
  content += `\n- ${v}`;
  pre.textContent = content;
});
<label>Result:</label>
<pre id="result"></pre>