Related Tags

parallel array

# What are parallel arrays?

Rukhshan Haroon

Parallel arrays are a group of arrays of the same size. Each element in each array at the same index corresponds to a different characteristic of the same subject of interest.

## Functionality

For example, let’s consider an array that contains the first names of five students. Similarly, let’s declare another array that contains the last names of the same five students. Since these are parallel arrays, the last name in the 0th index must belong to the first name in the 0th index of the first array.

In the same way, we can have more arrays of the same size that contain other characteristics of interest to us. For example, we can declare another array that contains the ages of the same five students. However, we must note that the number in the 0th index of the third array must be the student’s age, whose first name is stored at the 0th index of the first array.

This sequence must be followed for the rest of the elements of all the arrays.

## Application

Parallel arrays come in handy when data regarding different characteristics of the same subject of interest needs to be stored and accessed efficiently.

The diagram below shows two parallel arrays. The first array stores product names, and the second array stores the price of each product.

More specific applications of parallel arrays are:

• sorting: By sorting only one array, we can sort the rest of the parallel arrays (through side-by-side swapping of array elements of other arrays) simultaneously.
• searching: Once the target array element is found in one array, we can use indexing to access other characteristics of our subject of interest stored in the rest of the parallel arrays.

## Example

The program below implements four parallel arrays. The first, second, third, and fourth arrays store the names, ages, grades, and the subjects of five students, respectively.

Due to the semantics of parallel arrays, each array is of the same size, and each array element at the same index in all four arrays corresponds to the same student, who will be our subject of interest.

Using one for loop, all characteristics of each student are accessed and printed using the console.log function.

fname = ["John", "Michael", "Sara", "Zubair", "Sadia"]
age = [5,10,15,20,25]
subject =  ['English', 'Math', 'History', 'Physics', 'Chemistry']
for (i = 0; i < fname.length; i++) {
console.log("My name is", fname[i], ". I am", age[i], "years old. I have an", grade[i],"in my favorite subject:", subject[i],"!")
}

RELATED TAGS

parallel array

CONTRIBUTOR

Rukhshan Haroon 