Creating an associative array in JavaScript with push()?

An associative array in JavaScript is essentially an object that uses string keys to store arrays of values. You can create this structure by combining forEach() loops with the push() method to group related data.

Example: Grouping Students by ID

Here's how to create an associative array that groups student names by their student ID:

var studentDetails = [
    {
        studentId: 1,
        studentName: "John"
    },
    {
        studentId: 1,
        studentName: "David"
    },
    {
        studentId: 2,
        studentName: "Bob"
    },
    {
        studentId: 2,
        studentName: "Carol"
    }
];

var studentObject = {};

studentDetails.forEach(function (obj) {
    studentObject[obj.studentId] = studentObject[obj.studentId] || [];
    studentObject[obj.studentId].push(obj.studentName);
});

console.log(studentObject);
{ '1': [ 'John', 'David' ], '2': [ 'Bob', 'Carol' ] }

How It Works

The forEach() loop processes each student object:

  1. studentObject[obj.studentId] = studentObject[obj.studentId] || []; creates an empty array if the key doesn't exist
  2. studentObject[obj.studentId].push(obj.studentName); adds the student name to the appropriate array

Alternative Using Modern JavaScript

You can achieve the same result using reduce() for a more functional approach:

var studentDetails = [
    { studentId: 1, studentName: "John" },
    { studentId: 1, studentName: "David" },
    { studentId: 2, studentName: "Bob" },
    { studentId: 2, studentName: "Carol" }
];

var studentObject = studentDetails.reduce((acc, obj) => {
    acc[obj.studentId] = acc[obj.studentId] || [];
    acc[obj.studentId].push(obj.studentName);
    return acc;
}, {});

console.log(studentObject);
{ '1': [ 'John', 'David' ], '2': [ 'Bob', 'Carol' ] }

Conclusion

Creating associative arrays with push() is useful for grouping data by keys. The forEach() method provides a clear, readable approach to build these structures from existing arrays.

Updated on: 2026-03-15T23:18:59+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements