Implement the function deleteArrayElements() that reads N elements from the array starting from the given start index i and deletes every x-th element within this sub-array. The parameter startIndex can be greater than the length of the array. Implement a continuous addressing by looping through the array from the beginning again. The parameter everyIth can also be greater than the length of the array. However, at least one element, namely the 0-th element of the sub-array, should always be deleted. Return both the array without the deleted elements and the deleted elements

function deleteArrayElements(number, startIndex, everyIth) {
  let array = [];  
  let result = [];
  let removedItems = [];


  if (startIndex > array.length) {
    startIndex = startIndex % array.length;
  }

  for (let i = startIndex; i < startIndex + number; i += everyIth) {
    let indexToRemove = i % array.length;
    removedItems.push(array[indexToRemove]);
    array.splice(indexToRemove, 1);
  }

  result = array;
  return { newResult: result, removedItems: removedItems };
}

the expected output is {"newResult":[null, "katze", null, "elefant", null, "stachelschwein", "affe", "giraffe"], "removedItems":["hund", "maus", "schlange"]}; but the output I get is: {"newResult":["hund", "katze", "maus", "elefant", "schlange", "stachelschwein", "affe", "giraffe"], "removedItems":["hund", "elefant", "affe"]}

1

There are 1 best solutions below

4
James On

Using splice won't add null in place of the element that was removed. Since the length of the newResult should be the same as the length of array, using Array.map is a decent plan:

let array = ["hund", "katze", "maus", "elefant", "schlange", "stachelschwein", "affe", "giraffe"];

function deleteArrayElements(number, startIndex, everyIth) {
  let removedItems = [];
  let result = array.map((el, i) => {
    if (i >= startIndex && i < startIndex + number && (i - startIndex) % everyIth === 0) {
      removedItems.push(el);
      return null;
    } else {
      return el;
    }
  });

  return { newResult: result, removedItems: removedItems };
}

console.log(deleteArrayElements(6, 0, 2));
console.log(deleteArrayElements(5, 7, 13));