DEV Community

Judith ☁ Oiku
Judith ☁ Oiku

Posted on • Updated on

Jagged Array in JavaScript

Working with jagged array in most programming languages can be a bit clumsy , but the case is literally not the same for JavaScript because we easily get the length of the any row. You may be wondering what in the world is a jagged array, its fine, I presume this is your first time hearing it.

A ragged array, also known as a jagged array, is an array of arrays of which the member arrays can be of different sizes and producing rows of jagged edges when visualized as output. — Wikipedia

To give a clear understanding, lets imagine the measurement array where students have an unequal number of measurements recorded. We can still compute the correct average for each student without changing the program

var measurements = [[22, 10],[10, 13, 15, 14],[5, 27, 33]];
var total = 0;
var average = 0.0;
for (var row = 0; row < measurements.length; row++) {
    for (var col = 0; col < measurements[row].length; col++) {
   total += measurements[row][col];
average = total / measurements[row].length;
console.log(`Student ${parseInt(row+1)} average is  ${average.toFixed(2)}`);
total = 0;
average = 0.0;
Enter fullscreen mode Exit fullscreen mode

observe that the first student only has two measurements, while the second student has four measurements, and the third student has three measurements respectively. Here is the output from the program:

Alt Text

Originally published on my personal blog

Top comments (3)

aminnairi profile image

Interesting, I didn't even know it had a name.

Thanks for sharing!

I think that by using a forEach loop, you can decrease the need for using intermediate variables and ease the reading of the algorithm.

"use strict";

const students = [
    [ 18 ],
    [ 16, 12, 8 ],
    [ 2, 12 ]

students.forEach((grades, index) => {
    const rank = index + 1;
    const total = grades.reduce((sum, grade) => sum + grade, 0);
    const average = total / grades.length;

    console.log(`Student ${rank} average is ${average}.`);

// Student 1 average is 18.
// Student 2 average is 12.
// Student 3 average is 7.

What do you think?

osejudith profile image
Judith ☁ Oiku

Am glad you found it resourceful, Yeah, you are right, thanks so much for sharing

siyadkundala profile image

Thanks. It's very helpful...