0

I'm having an issue of understanding and I'll try to be basic with my problem because it involves lots of data. Here is a simple mockup.

From myArray below, I'm trying to create a new 2D array (arrayFinal) in the form of [[element],[element],[element]], to be able to use a setValues() with Excel Office Script. In this example, each element should have more than 2 elements.

But I'm truly not going anywhere with my way.

I only get a return like, with too many [[[]]] (one too many), and only the last element repeating itself.

[[[1,5,7]],[[1,5,7]],[[1,5,7]],[[1,5,7]],[[1,5,7]],[[1,5,7]]]

Could you have a look and tell me what's the problem ?

let myArray: number[][] = [[1, 2, 3], [2, 4], [5, 6, 7],[1],[2,3],[1,5,7]];

let testArray: (string | boolean | number)[][] = []; 
let arrayFinal: (string | boolean | number)[][] = []; 


myArray.map(x => {
    testArray.length = 0;
    if (x.length > 2) {

       
            testArray.push(x);

       
    }
    arrayFinal.push(testArray);
})
console.log(JSON.stringify(arrayFinal))

Thank you !

2
  • can you see this? stackoverflow.com/questions/11345954/… Commented Nov 13, 2021 at 21:21
  • Thanks for the advice, I still hope I can do this with a map/foreach or any of these methods Commented Nov 13, 2021 at 23:05

1 Answer 1

0

If I understand it correctly, you are trying to filter the original 2D array to only contain sub-arrays with more than 2 elements, right?

Wondering if you would want to try something like this:

let myArray: number[][] = [[1, 2, 3], [2, 4], [5, 6, 7],[1],[2,3],[1,5,7]];
let arrayFinal = myArray.filter(arr => arr.length > 2);
console.log(JSON.stringify(arrayFinal))

The output should be:

[[1,2,3],[5,6,7],[1,5,7]]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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