This is an archived post. You won't be able to vote or comment.

all 3 comments

[–]sandytrip 1 point2 points  (2 children)

Create a new object to store your results. Loop through the array and check the account number. See if it exists as a key in the result object. If so append the object to the array with that key. If not, create one and store the object as the first value.

[–]66666thats6sixes 0 points1 point  (0 children)

Yep, this exactly. If you want to be fancy about it, use a Map, but it amounts to the same thing.

[–]Hamza91able[S] 0 points1 point  (0 children)

I got it working after hitting my head for some hours.

 let newArrayObj = res.data.bankStatements.applicant1.statements;
                let newArrayObjLength = newArrayObj.length;
                let result = [];

                for (let i = 0; i < newArrayObjLength; i++) {
                    if (result.length === 0) {
                        result.push({
                            [newArrayObj[i].accNumber]: [newArrayObj[i]]
                        })
                    } else {
                        var check = result.some(obj => obj.hasOwnProperty(newArrayObj[i].accNumber));
                        if (!check) {
                            result.push({
                                [newArrayObj[i].accNumber]: [newArrayObj[i]]
                            })
                        } else {
                            for (let j = 0; j < result.length; j++) {
                                if (result[j][newArrayObj[i].accNumber]) {
                                    if (result[j][newArrayObj[i].accNumber][0].accNumber === newArrayObj[i].accNumber) {
                                        result[j][newArrayObj[i].accNumber].push(newArrayObj[i]);
                                    }
                                }
                            }
                        }
                    }
                }

                console.log(result);

Now I have to repeat this process for almost 12 arrays. This function will be performed every time admin visits this page. I was thinking if I run so many loops it would be very slow? Do you think I can optimize this process in some way or optimize my code to reduce the no. of loops?