2

I have a Javascript array which I wanted to slice and put in a new array, but the new array prints out only the last value.

I tried using for loop

let array = [5, 6, 9, 7, 10, 17, 20, 35, 105, 140];
let slicedArray;
const removeNumbers = () => {
  for (let i = 0; i < array.length; i++) {
    if (array[i] % 5 === 0 && array[i] % 7 === 0) {
      slicedArray = [...array.splice(i, 1)];
    }
  }
  return slicedArray;
}

console.log(removeNumbers());

I expected 35,105, and 140 as an output, but the actual output is just 140.

2
  • 4
    Because you are always resetting slicedArray's value slicedArray=[...], not appending (pushing) to it Sep 21, 2019 at 21:48
  • Why do you want 7 to be included in your desired output? It's not a multiple of 5 Sep 21, 2019 at 21:49

6 Answers 6

1

Use .filter instead, to create a new array based on elements of a different array that pass a test:

let array = [5, 6, 9, 7, 10, 17, 20, 35, 105, 140];
const newArr = array.filter(num => num % 5 === 0 && num % 7 === 0);
console.log(newArr);

If you have to mutate the existing array as well, then push the spliced element to the new array while splicing (don't reassign the slicedArray, just push to it):

const array = [5, 6, 9, 7, 10, 17, 20, 35, 105, 140];
const removeNumbers = () => {
  const slicedArray = [];
  for (let i = 0; i < array.length; i++) {
    if (array[i] % 5 === 0 && array[i] % 7 === 0) {
      slicedArray.push(...array.splice(i, 1));
      // Need to subtract 1 from i here, so that this removed index gets iterated over again next time
      i--;
    }
  }
  return slicedArray;
}


console.log(removeNumbers());

7 is not included because it's not a multiple of 5.

2
  • Thank you very much! This is really helpful! Yes, I said 7 by mistake.
    – mimi ethio
    Sep 21, 2019 at 21:59
  • When an answer solves your problem, you may consider marking it as Accepted (click the checkbox) to indicate that the issue is resolved :) Sep 22, 2019 at 6:13
0

Try pushing the elements in the array like this:

let array = [5,6,9,7,10,17,20,35,105,140];
let slicedArray;    
const removeNumbersTest = () => {
 for(let i = 0; i < array.length; i++){
   if(array[i] % 5 === 0 && array[i] % 7 === 0){
     slicedArray.push(...array.splice(i,1));
     }
   }
   return slicedArray;
}

The code above should do what you wanted it to do, just check the logic before pushing the elements in the array.

Hope it helps!

2
  • 1
    I tried this before, it doesn't work. It nests the new array into another array. Thanks though! I found the solution now.
    – mimi ethio
    Sep 21, 2019 at 22:12
  • @Ruan Montelo your code is wrong you are mutating the object it should be like this slicedArray.push(...[...array].splice(i, 1)); Also you did not assign the value of array to you slicedArray variable which will cause an error when trying to push
    – EugenSunic
    Sep 21, 2019 at 22:24
0

You should only be getting 35, 105 and 140 according to your if statement. Since you want your numbers to bi divisible by 5 and 7.

The problem was you did not append your numbers in the array and mutated the array when using splice method. Because of mutation number 105 wasn't included.

let array = [5, 6, 9, 7, 10, 17, 20, 35, 105, 140];
let slicedArray = [];
const removeNumbers = () => {
  for (let i = 0; i < array.length; i++) {
    if (array[i] % 5 === 0 && array[i] % 7 === 0) {

      slicedArray = [...slicedArray, ...[...array].splice(i, 1)];

    }

  }

  return slicedArray;
}


console.log(removeNumbers());
2
  • My bad, I meant 35,105, and 140. 105 satisfies the condition too.
    – mimi ethio
    Sep 21, 2019 at 21:56
  • @mimiethio check my code again, the problem was that you mutated you array
    – EugenSunic
    Sep 21, 2019 at 22:02
0

You simply can push the target items on the slicedArray:

let array =[5,6,9,7,10,17,20,35,105,140];
const slicedArray=[];  //Array is mutable with const keyword
const removeNumbers= () =>{
    for(let i=0; i<array.length; i++){
        if(array[i] % 5 === 0 && array[i] % 7 === 0){

          slicedArray.push(array[i]);

         }

    }

    return slicedArray;
}


console.log(removeNumbers());
0

Two problems with your code and some minor issues:

  1. array.slice() returns removed items and you have to collect them sequentially.
    Solution: Push the items returned from array.slice() to the collecting array using array.push().

  2. array.slice() modifies the array in place. Say the current index i is set to 7, that item 35 gets removed by the slicing operation from array. But now the next number 105 is shifted one position downwards. The for-loop continues with index 8 which now contains number 140.
    Solution: Modify the for-loop index when an item is removed.

  3. The naming slicedArray is misleading. Better name would be removedNumbers.

  4. The variable removedNumbers should be a local to the function removeNumber().

  5. Using a global variable array is not perfect. Maybe you would like to change your code to removeNumbers() takes a parameter. I omitted this fix from my example.

A fixed solution could look like:

(Please note the i-- which fixes the index to test in the next for-loop iteration the same position again.)

let array = [5,6,9,7,10,17,20,35,105,140];

const removeNumbers = () => {
  let removedNumbers = [];

  for(let i=0; i<array.length; i++){
    if(array[i] % 5 === 0 && array[i] % 7 === 0) {

      removedNumbers.push(...array.splice(i--,1));

    }
  }
  return removedNumbers;
}

console.log("Removed numbers:", removeNumbers());
console.log("Remaining numbers:", array);
-1

If you expect 7, 35,105, and 140 then append to the list and change your if to

if (array[i] % 7 === 0 && array[i] % 5 === 0)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.