0

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.

2 Answers 2

2

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);

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

Comments

1

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)
  )
);

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.