0

For example I have a chunks array, this array has the sizes of individual chunks.

let example = [3,3]; // Chunks array
let auxarrayindex = [1,2,3,4,5,6]; // Array that I want to splice
let example2 = [3,2,3]; // Chunks array
let auxarrayindex2 = [1,2,3,4,5,6,7,8]; // Array that I want to splice

The result that I want is:

[1,2,3],[4,5,6] and the second [1,2,3],[4,5],[6,7,8]

This is my code:

for (let auxexample = 0; auxexample < example.length; auxexample++) {
    finalauxarray.push(auxarrayindex.slice(0, example[auxexample]));
}

The result from my code is:

[1,2,3],[1,2,3] and the second [1,2,3],[1,2],[1,2,3]

3 Answers 3

6

The problem is that your slice always starts at the same index (0).

Use a variable (like i) that you increase as you take chunks:

let example = [3,2,3];
let auxarrayindex = [1,2,3,4,5,6,7,8];

let finalauxarray = [];
let i = 0;
for (let auxexample = 0; auxexample < example.length; auxexample++) {
   finalauxarray.push(auxarrayindex.slice(i, i+=example[auxexample]));
}

console.log(finalauxarray);

You could also use map for your loop:

let example = [3,2,3];
let auxarrayindex = [1,2,3,4,5,6,7,8];

let i = 0;
let finalauxarray = example.map(size => auxarrayindex.slice(i, i+=size));

console.log(finalauxarray);

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks!! a simple method
3

The problem is because of the slice parameters are wrong You can learn more about how slice works on this link

https://www.w3schools.com/jsref/jsref_slice_array.asp

It takes as first parameter the starti g position and as last parameter the ending position which is not included in the result

You can aslo use splice for this as well https://www.w3schools.com/jsref/jsref_splice.asp

Hope that helps

Comments

2

Working example using splice instead of slice as I think it offers a slightly cleaner API for this particular use-case:

let example = [3, 3];
let auxArrayIndex = [1, 2, 3, 4, 5, 6];
let example2 = [3, 2, 3];
let auxArrayIndex2 = [1, 2, 3, 4, 5, 6, 7, 8];

function getChunks(chunkSizes, array) {
  let result = [];
  for (let chunkSize of chunkSizes) {
    result.push(array.splice(0, chunkSize));
  }
  return result;
}

let chunks = getChunks(example, auxArrayIndex);
let chunks2 = getChunks(example2, auxArrayIndex2);

console.log(chunks); // logs "[1,2,3], [4,5,6]"
console.log(chunks2); // logs "[1,2,3], [4,5], [6,7,8]"

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.