JavaScript Program to Sort an Associative Array by its Values
Last Updated :
28 May, 2024
In Javascript, "arrays" are indexed by numerical values, while "objects" are essentially what you might refer to as associative arrays. It's important to note that "objects" do not have a guaranteed order. In this article, we will learn how can we sort an associative array by its values.
Using sort() method
In this approach, we create a sorting function that has its own comparator which basically sorts the array based on the value property that we provide to it. This will help to achieve the sorting on the array we defined by making little changes in the structure.
Example 1: This example shows the use of the above-explained approach.
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 }
]
Time Complexity : O(n), because it iterates over an array and compares over each of the entries of the array.
Space Complexity: O(1), because there is no extra space required and neither any recursive call.
Example 2: In this example, we will create array with the dynamic method and in the comparator function instead of substracting values we check for greater and compare.
JavaScript
let list = new Array();
list.push({ key: 'a', value: 101 });
list.push({ key: 'b', value: 43 });
list.push({ key: 'd', value: 42 });
list.push({ key: 'k', value: 71 });
list.sort(function (a, b) {
if (a.value > b.value) {
return -1;
}
else if (a.value < b.value) {
return 1;
}
return 0;
});
console.log(list);
Output[
{ key: 'a', value: 101 },
{ key: 'k', value: 71 },
{ key: 'b', value: 43 },
{ key: 'd', value: 42 }
]
Time Complexity : O(n), because it iterates over an array and compares over each of the entries of the array.
Space Complexity: O(1), because there is no extra space required and neither any recursive call.
In this approach, we will first convert the associative array into an array of key-value pairs using Object.entries. This will generate array of arrays in which sub-array contains a key-value pair. Then we will sort the array such that it sorts the array in ascending order based on the second element of each sub-array. Then use reduce function to convert the sorted array back into an object.
Example: This example shows the use of the above-explained approach.
JavaScript
const a = {
a: 90,
e: 12,
o: 27,
};
const arr = Object.entries(a);
arr.sort((a, b) => a[1] - b[1]);
const res = arr.reduce((acc, [key, value]) => {
acc[key] = value;
return acc;
}, {});
console.log(res)
Output{ e: 12, o: 27, a: 90 }
In this approach, we will first convert the associative array into an array of keys using Object.keys. This will generate array of keys. Then we will sort the array. Then use reduce function to convert the sorted array back into an object.
Example: This example shows the use of the above-explained approach.
JavaScript
const arr = {
b: 3,
a: 1,
d: 2,
};
const keys = Object.keys(arr);
const sarr = keys.sort((a, b) => arr[a] - arr[b]);
const obj = sarr.reduce((acc, key) => {
acc[key] = arr[key];
return acc;
}, {});
console.log(obj);
Output{ a: 1, d: 2, b: 3 }
Using Object.keys() and Array.map()
Using Object.keys() to extract keys, then Array.map() to create an array of key-value pairs. Sort this array by values. Finally, Array.reduce() converts it back to an object.
Example: In this example the function sortObjectByValues sorts an object's entries by their values in ascending order.
JavaScript
function sortObjectByValues(obj) {
return Object.keys(obj)
.map(key => [key, obj[key]])
.sort((a, b) => a[1] - b[1])
.reduce((acc, [key, value]) => {
acc[key] = value;
return acc;
}, {});
}
let obj = { a: 3, b: 1, c: 2 };
console.log(sortObjectByValues(obj));
Output{ b: 1, c: 2, a: 3 }
Similar Reads
JavaScript Program to Sort Words in Alphabetical Order
Sorting words in alphabetical order involves arranging them based on the standard sequence of letters in the alphabet. This process helps in organizing data, making searches efficient, and presenting information in a clear and systematic manner.Methods to sort wordsTable of Content Approach 1: Using
5 min read
JavaScript Program for Insertion Sort
What is Insertion Sort Algorithm?Insertion sorting is one of the sorting techniques that is based on iterating the array and finding the right position for every element. It compares the current element to the predecessors, if the element is small compare it with the elements before. Move ahead to a
4 min read
JavaScript Program to Sort Strings in Alphabetical Order Ignoring Case
In this article, we are given an array of strings, you need to sort the given array of strings containing both uppercase and lowercase characters in ascending order by ignoring the case in JavaScript. Example 1: Input :- arr = ["Geeks", "for", "geeks", "is", "The", "Best"] Output :- [ 'Best', 'for',
3 min read
JavaScript Program for Quick Sort
What is Quick Sort Algorithm?Quick sort is one of the sorting algorithms that works on the idea of divide and conquer. It takes an element as a pivot and partitions the given array around that pivot by placing it in the correct position in the sorted array. The pivot element can be selected in the f
4 min read
Javascript Program to Sort an array in wave form
Given an unsorted array of integers, sort the array into a wave like array. An array 'arr[0..n-1]' is sorted in wave form if arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4] >= .....Examples: Input: arr[] = {10, 5, 6, 3, 2, 20, 100, 80} Output: arr[] = {10, 5, 6, 2, 20, 3, 100, 80} OR {
4 min read
How to Sort JSON Array in JavaScript by Value ?
Sorting is the process of arranging elements in a specific order. In JavaScript, you can sort a JSON array by value using various methods as listed and discussed below with their practical implementation. Table of Content Using sort() FunctionUsing Array.prototype.reduce()Using Bubble SortUsing sort
3 min read
What are Associative Arrays in JavaScript ?
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: "Ge
2 min read
Java Program to Sort a HashMap by Keys and Values
HashMap<K, V> is a Java Collection and is a part of java.util package. It provides the basic implementation of the Map interface of Java. It stores the data in the form of Key, Value pairs, where the keys must be unique but there is no restriction for values. If we try to insert the duplicate
3 min read
Sort an Associative Array by Key in PHP
Given an Associative Array, the task is to sort the associative array by its keys in PHP. There are different methods to sort Associative Array by keys, these are described below: Table of ContentUsing ksort() FunctionUsing uksort() FunctionConverting to a Regular Array for SortingUsing array_multis
3 min read
Java Program to Sort an ArrayList
ArrayList is the class provided in the Collection framework. In Java, the collection framework is defined in java.util package. ArrayList is used to dynamically stores the elements. It is more flexible than an array because there is no size limit in ArrayList. ArrayList stores the data in an unorder
6 min read