Open In App

What are Associative Arrays in JavaScript ?

Last Updated : 10 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Associative arrays in JavaScript, commonly referred to as objects, are crucial for storing key-value pairs. This guide explores the concept and usage of associative arrays, providing insights into their benefits and applications.

Example:

// Creating an associative array (object)
let arr= {
name: "Geek",
age: 10,
city: "Noida"
};
// Accessing values using keys
console.log(person.name);
console.log(person.age);
console.log(person.city);

We will perform some operations on associative arrays now:

Example 1: In this example, we will Calculate the length of an associative array.

JavaScript
let arr = { "apple": 10, "grapes": 20 };
arr["guava"] = 30;
arr["banana"] = 40;

// Printing the array 
// returned by keys() method
console.log(Object.keys(arr))

// printing the size
console.log("Size = " + Object.keys(arr).length)

Output
[ 'apple', 'grapes', 'guava', 'banana' ]
Size = 4

Example 2: In this example, we will see how to Sort an Associative Array by its Values

JavaScript
let a = []; // Array 

// Add elemets to it 
a.push({ name: 'a', class: 1 });
a.push({ name: 'b', class: 9 });
a.push({ name: 'c', class: 2 });
a.push({ name: 'd', class: 6 });

// Custom sorting function 
let sortedList = a.sort(function (a, b) {
    return a.class - b.class;
});

// Output 
console.log(sortedList);

Output
[
  { name: 'a', class: 1 },
  { name: 'c', class: 2 },
  { name: 'd', class: 6 },
  { name: 'b', class: 9 }
]

Example 3: In this example, we will see how to list of associative array keys in JavaScript.

JavaScript
// Input Associative Array
let arr = {
    Newton: "Gravity",
    Albert: "Energy",
    Edison: "Bulb",
    Tesla: "AC",
};

// getting keys using getOwnPropertyNames
const keys = Object.getOwnPropertyNames(arr);
console.log("Keys are listed below ");

// Display output
console.log(keys);

Output
Keys are listed below 
[ 'Newton', 'Albert', 'Edison', 'Tesla' ]

Common Use Cases:

While detailed examples will be discussed in the approaches section, here’s a brief overview:

  • Dynamic Property Assignment: Adding or updating properties dynamically.
  • Data Storage and Retrieval: Efficiently managing and accessing data with named keys.

Understanding associative arrays in JavaScript is essential for effective data management and manipulation. This guide introduces the importance and prerequisites, preparing you for deeper exploration of their usage. By focusing on practical applications, you can improve your JavaScript proficiency and code efficiency.


Next Article

Similar Reads