Search code examples
javascriptsplice

splice inside for loop return wrong values JAVASCRIPT


I want to divide the content of my array into 4, for this i first need to know what would be the content of each divided array set, i use Math.ceil for this.

results = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']; #lenght is 8
let half = Math.ceil(results.length / 4) # half is 2
let whole = [] #i want to insert the spliced value into this array
let j = 0;
let x
for (i = 0; i < 4; i++) {
    console.log("j:" + j)
    console.log("half: " + half)
    x = results.splice(j, half)
    console.log(x)
    j = j + half;
}

this is my wrong output:

j:0
half: 2
[ 'a', 'b' ] #this is correct
j:2
half: 2
[ 'e', 'f' ] #this is wrong, it should be ['c','d']
j:4
half: 2
[] #this is wrong, should be ['e','d']
j:6
half: 2
[]#also wrong, should be ['f','g',]

When i test this outside of the for loop it works fine, using index 0,2 - 2,2 - 4, 2 -6,2. what might be the error?


Solution

  • Splice method change the content of the array(by removing, replacing or adding). You should use slice with the end upto i * 2 + half

    results = ["a", "b", "c", "d", "e", "f", "g", "h"]; // #lenght is 8
    let half = Math.ceil(results.length / 4); // # half is 2
    let whole = []; //#i want to insert the spliced value into this array
    let j = 0;
    let x;
    for (i = 0; i < 4; i++) {
    
      // change the end so that it will take next 2 element pos dynamically
      const end = i * 2 + half;
      x = results.slice(j, end);
      j = j + half;
      whole.push(x);
    }
    
    console.log(whole);