JavaScript Associative arrays are basically objects in which indexes are replaced by user-defined keys. Javascript associative arrays do not have a length property like normal arrays and cannot be traversed using a normal for loop.
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' ]