0

Good day, I have been trying to solve JS problem where I have an array a = [1, 1, 1, 2, 1, 3, 4]. I have to loop through an array and remove every three elements ie (1,1,1) do some logic, then the next three (1,1,2), and so on.

I have used for loop and splice

a = [1, 1, 1, 2, 1, 3, 4]
tuple = ()

    for(j=0; j < a.length; j++){
        tuple = a.splice(j, 3)
    }

However, loop would not go beyond first round of (1,1,1). What would be the correct way to loop through this array and remove sets of every three elements. thank you.

Alexey
  • 51
  • 5
  • 1
    Are you asking "How can I iterate over each set of 3 consecutive elements?" – tadman Mar 18 '21 at 11:09
  • where do you get `(1,1,2)` from? – Nina Scholz Mar 18 '21 at 11:10
  • 1
    Maybe something [like this](https://stackoverflow.com/questions/57477912/equivalent-of-rubys-each-cons-in-javascript)? – tadman Mar 18 '21 at 11:11
  • `.splice`ing an array while looping through it requires careful implementation (`.splice` mutates the array) – FZs Mar 18 '21 at 11:14
  • @tadman. yes I need to iterate over each set of 3 consec elements. out of array 'a' I have to remove 3 elements (1,1,1,) do some logic, and then take the next 3 (1,1,2) and repeat again. – Alexey Mar 18 '21 at 12:34
  • Right, so did that answer help? – tadman Mar 18 '21 at 12:35
  • No, I probably don't understand what they are saying in the link you sent. If you could explain? thanks. – Alexey Mar 18 '21 at 12:40
  • @NinaScholz (1,1,2) is an example of what I have to get out of array a. it's the first three elements. – Alexey Mar 18 '21 at 12:43

2 Answers2

1

Splice return removed elements from base array in given range. You probable want to use slice which only copy them and doesn't change primary array. You can also check this solution.

let a = [1, 1, 1, 2, 1, 3, 4];

for (j = 0; j < a.length; j++) {
    if ( j < a.length - 2 ) {
        const touple = [ a[j], a[j+1], a[j+2] ]
        console.log( touple )
    }
}
Kishieel
  • 1,811
  • 2
  • 10
  • 19
0

splice changes the original array and that must be causing your issue.

So, you can use slice which returns a shallow copy of a portion of the original array (without modifying the original array):

const a = [1, 1, 1, 2, 1, 3, 4]

const doLogic = (arr) => {
  console.log(JSON.stringify(arr)) // JSON.stringify is only for one-liner print. You can ignore it.
}

for (let i = 0; i < a.length - 2; i++) {
  const picked = a.slice(i, i + 3)
  doLogic(picked)
}

Or this, if you want to pick the full array when length is less than 3:

if (a.length < 3) {
  doLogic(a)
} else {
  for (let i = 0; i < a.length - 2; i++) {
    const picked = a.slice(i, i + 3)
    doLogic(picked)
  }
}
Ajeet Shah
  • 18,551
  • 8
  • 57
  • 87