How to generate array key using array index – JavaScript associative array?

In JavaScript, you can create associative arrays (objects) using array indices as keys. This is useful for mapping array elements to their positions or creating key-value pairs from existing arrays.

Using forEach() Method

The forEach() method provides access to both the element and its index, allowing you to create dynamic object properties:

var result = {};
var names = ['John', 'David', 'Mike', 'Sam', 'Bob', 'Adam'];

names.forEach((nameObject, counter) => {
    var generatedValues = { [nameObject]: counter };
    Object.assign(result, generatedValues);
});

console.log(result);
{ John: 0, David: 1, Mike: 2, Sam: 3, Bob: 4, Adam: 5 }

Alternative Methods

Using reduce() Method

A more concise approach using reduce():

var names = ['John', 'David', 'Mike', 'Sam', 'Bob', 'Adam'];

var result = names.reduce((acc, name, index) => {
    acc[name] = index;
    return acc;
}, {});

console.log(result);
{ John: 0, David: 1, Mike: 2, Sam: 3, Bob: 4, Adam: 5 }

Using Simple Loop

var names = ['John', 'David', 'Mike', 'Sam', 'Bob', 'Adam'];
var result = {};

for (let i = 0; i < names.length; i++) {
    result[names[i]] = i;
}

console.log(result);
{ John: 0, David: 1, Mike: 2, Sam: 3, Bob: 4, Adam: 5 }

Comparison of Methods

Method Readability Performance Use Case
forEach() + Object.assign() Moderate Slower When you need complex operations
reduce() Good Good Functional programming style
for loop Good Fastest Simple transformations

Conclusion

Use reduce() for clean, functional code or a simple for loop for better performance. The forEach() approach works but is less efficient due to multiple object assignments.

Updated on: 2026-03-15T23:19:00+05:30

381 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements