Siva Pradhan
Siva Pradhan

Reputation: 861

Calculate length of specific key's array within array of array

Suppose I have an array of array and an empty array:

const sampleArray = [ [{"book":["harry pottar","lotr"]},{"book":["omega","beta"]}] , 
                      [{"book":["ronjan","pirates","simba"]},{"book":["musical","eskobar","elsa"]}],
                      [{"book":["book1","book2","book3"]},{"book":["book4","book5"]}] ]

const emptyArray = []

What I want is to push the total length of book of first element of array as one, second element of array as one, third as one and so on. Such that O/P looks like:

console.log(emptyArray) => [4,6,5] => total length of book for each element of array.

For this, I tried as,

for(let i =0; i<sampleArray.length;i++){
    for(let j = 0; j<sampleArray[i].length;j++){
        emptyArray.push(sampleArray[i][j].book.length)
    }
}

But it just pushes length for each books as: [2,2,3,3,3,2].

I'm unable to get to the logic where I can merge two book's array into one.

If anyone needs any further information please do let me know.

Upvotes: 0

Views: 29

Answers (2)

nyarthan
nyarthan

Reputation: 535

yes it is possible using array.map with arry.reduce

const sampleArray = [
  [{ book: ["harry pottar", "lotr"] }, { book: ["omega", "beta"] }],
  [{ book: ["ronjan", "pirates", "simba"] }, { book: ["musical", "eskobar", "elsa"] }],
  [{ book: ["book1", "book2", "book3"] }, { book: ["book4", "book5"] }]
];

console.log(
  sampleArray.map((element) =>
    element.reduce((acc, cur) => cur.book.length + acc, 0)
  )
);

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370729

While you could declare a count variable that you add to in the first loop:

for(let i =0; i<sampleArray.length;i++){
    let count = 0;
    for(let j = 0; j<sampleArray[i].length;j++){
        count += sampleArray[i][j].book.length;
    }
    emptyArray.push(count)
}

It'd be more elegant to map each outer subarray with .map, and count up lengths with reduce:

const sampleArray = [ [{"book":["harry pottar","lotr"]},{"book":["omega","beta"]}] , 
                      [{"book":["ronjan","pirates","simba"]},{"book":["musical","eskobar","elsa"]}],
                      [{"book":["book1","book2","book3"]},{"book":["book4","book5"]}] ]

const emptyArray = sampleArray.map(
  subarr => subarr.reduce((a, b) => a + b.book.length, 0)
);
console.log(emptyArray);

Upvotes: 2

Related Questions