0

Need to format my array for chart purpose

myArr=[["6709"],["1949"],["87484"],["12760"],["13326"],["3356"],["98000"],["16949"],["29981"],["7879"],["117640"],["30727"],["122071"],["21325"],["210406"],["65824"],["2744807"],["56664"],["382719"],["134578"],["2440528"],["83819"],["1362744"],["450092"],["2461"],["336"],["166446"],["16363"]]

Below Formatted Array

formatArr= [["6709", "1949", "87484", "12760"], ["13326", "3356", "98000", "16949"], ["29981", "7879", "117640", "30727"], ["122071", "21325", "210406", "65824"], ["2744807", "56664", "382719", "134578"] ["2440528", "83819", "1362744", "450092"], ["2461", "336", "166446", "16363"]]
1
  • Is there a criteria for the grouping ? Commented Mar 10, 2021 at 15:54

2 Answers 2

1

You could reduce it like this for example:

const formatArr: string[][] = myArr.reduce((prev, item, index) => {
    if (index % 4 === 0) {
        // every fourth item creates a new array with the current item:
        prev.push(item);
    } else {
        // every other item pushes to the previously added item:
        prev[prev.length - 1].push(item[0]);
    }
    return prev;
}, [] as string[][]);
Sign up to request clarification or add additional context in comments.

3 Comments

am getting this error core.js:6228 ERROR TypeError: prev[(prev.length - 1)].push is not a function
got a fiddle or playground link?
@ Mr.Manhattan, Fixed.
0

        myArr = [["6709"],["1949"],["87484"],["12760"],["13326"],["3356"],["98000"],["16949"],["29981"],["7879"],["117640"],["30727"],["122071"],["21325"],["210406"],["65824"],["2744807"],["56664"],["382719"],["134578"],["2440528"],["83819"],["1362744"],["450092"],["2461"],["336"],["166446"],["16363"]]
        formatArr = []

        function makeArray(params) {
            let element = [];
            for (let i = 0; i < myArr.length; i++) {
                element.push(myArr[i][0])
                if ((i + 1) % 4 == 0) {
                    formatArr.push(element);
                    element = [];
                }
            }
            console.log(formatArr);
        }

        makeArray();

This is correct if myArr has 4n element, if not use this

function makeArray(params) {
            let element = [];
            for (let i = 0; i < myArr.length; i++) {
                element.push(myArr[i][0])
                if ((i + 1) % 4 == 0) {
                    formatArr.push(element);
                    element = [];
                }
                if (i == myArr.length - 1 && (i + 1) % 4 != 0) {
                    formatArr.push(element);
                }
            }
            console.log(formatArr);
        }

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.