How to sort an array of object by two fields in JavaScript ? Last Updated : 26 Jun, 2024 Comments Improve Suggest changes Like Article Like Report We have given an array of objects and the task is to sort the array of elements by 2 fields of the object. There are two methods to solve this problem which are discussed below: Approach 1:First compare the first property, if both are unequal then sort accordingly.If they are equal then do the same for the second property.Example: This example implements the above approach with a custom comparison function. JavaScript // Create an array of objects let arr = [ { first: 3, second: 4 }, { first: 3, second: 1 }, { first: 1, second: 10 } ]; // Apply array.sort with comparison function arr.sort(function (a, b) { let af = a.first; let bf = b.first; let as = a.second; let bs = b.second; // If first value is same if (af == bf) { return (as < bs) ? -1 : (as > bs) ? 1 : 0; } else { return (af < bf) ? -1 : 1; } }); // Display output console.log("'" + JSON.stringify(arr[0]) + ", " + JSON.stringify(arr[1]) + ", " + JSON.stringify(arr[2]) + "'"); Output'{"first":1,"second":10}, {"first":3,"second":1}, {"first":3,"second":4}' Approach 2:First compare the first property, If both are unequal then sort accordingly.If they are equal then do the same for the second property, this example is following the same approach but uses OR Gate to reduce the code.Example: This example implements the above approach with a custom comparison function. JavaScript // Create input array of objects let arr = [ { first: 3, second: 4 }, { first: 3, second: 1 }, { first: 1, second: 10 } ]; // Apply array.sort with custom comparision funtion arr.sort(function (a, b) { // Compare first value then second return a.first - b.first || a.second - b.second; }); // Display the output console.log("'" + JSON.stringify(arr[0]) + ", " + JSON.stringify(arr[1]) + ", " + JSON.stringify(arr[2]) + "'"); Output'{"first":1,"second":10}, {"first":3,"second":1}, {"first":3,"second":4}' Approach 3: Using a Dynamic Comparison FunctionIn this approach, we create a dynamic comparison function that accepts the properties to sort by as parameters. This makes the function reusable for different sets of properties without hardcoding the property names. JavaScript function dynamicSort(properties) { return function(a, b) { for (let i = 0; i < properties.length; i++) { let prop = properties[i]; if (a[prop] < b[prop]) return -1; if (a[prop] > b[prop]) return 1; } return 0; } } const data = [ { name: 'John', age: 25 }, { name: 'Jane', age: 22 }, { name: 'John', age: 22 }, { name: 'Jane', age: 25 } ]; const sortedData = data.sort(dynamicSort(['name', 'age'])); console.log(sortedData); Output[ { name: 'Jane', age: 22 }, { name: 'Jane', age: 25 }, { name: 'John', age: 22 }, { name: 'John', age: 25 } ] Comment More infoAdvertise with us Next Article How to sort an array of object by two fields in JavaScript ? P PranchalKatiyar Follow Improve Article Tags : JavaScript Web Technologies javascript-array JavaScript-DSA JavaScript-Questions +1 More Similar Reads JavaScript - Find Index of a Value in Array Here are some effective methods to find the array index with a value in JavaScript.Using indexOf() - Most Used indexOf() returns the first index of a specified value in an array, or -1 if the value is not found. JavaScriptconst a = [10, 20, 30, 40, 50]; // Find index of value 30 const index = a.inde 2 min read JavaScript - How to Get First N Elements from an Array? There are different ways to get the first N elements from array in JavaScript.Examples:Input:arr = [1, 2, 3, 4, 5, 6], n = 3 Output: [1, 2, 3] Input:arr = [6, 1, 4, 9, 3, 5, 7], n = 4Output: [6, 1, 4, 9]1. Using slice() MethodThe slice() method is used to extract a part of an array and returns a new 4 min read How to Copy Array by Value in JavaScript ? There are various methods to copy array by value in JavaScript.1. Using Spread OperatorThe JavaScript spread operator is a concise and easy metho to copy an array by value. The spread operator allows you to expand an array into individual elements, which can then be used to create a new array.Syntax 4 min read What is the most efficient way to concatenate N arrays in JavaScript ? In this article, we will see how to concatenate N arrays in JavaScript. The efficient way to concatenate N arrays can depend on the number of arrays and the size of arrays. To concatenate N arrays, we use the following methods:Table of ContentMethod 1: Using push() MethodMethod 2: Using concat() Met 3 min read How to Merge Two Arrays and Remove Duplicate Items in JavaScript? Given two arrays, the task is to merge both arrays and remove duplicate items from merged array in JavaScript. The basic method to merge two arrays without duplicate items is using spread operator and the set constructor.1. Using Spread Operator and Set() ConstructorThe Spread Operator is used to me 3 min read How to clone an array in JavaScript ? In JavaScript, cloning an array means creating a new array with the same elements as the original array without modifying the original array.Here are some common use cases for cloning an array:Table of ContentUsing the Array.slice() MethodUsing the spread OperatorUsing the Array.from() MethodUsing t 6 min read JavaScript - Check if JS Array Includes a Value? To check if an array includes a value we can use JavaScript Array.includes() method. This method returns a boolean value, if the element exists it returns true else it returns false.1. Using Array.includes() Method - Mostly Used The JS array.includes() method returns true if the array contains the s 4 min read JavaScript - Create an Object From Two Arrays Here are the different methods to create an object from two arrays in JavaScript1. Using for-each loopThe arr.forEach() method calls the provided function once for each element of the array. JavaScriptconst a1 = ['name', 'age', 'city']; const a2 = ['Ajay', 25, 'New Delhi']; const res = {}; a1.forEac 3 min read How to remove falsy values from an array in JavaScript ? Falsy/Falsey Values: In JavaScript, there are 7 falsy values, which are given below falsezero(0,-0)empty string("", ' ' , ` `)BigIntZero(0n,0x0n)nullundefinedNaNIn JavaScript, the array accepts all types of falsy values. Let's see some approaches on how we can remove falsy values from an array in Ja 6 min read JavaScript - Use Arrays to Swap Variables Here are the different methods to swap variables using arrays in JavaScript1. Using Array DestructuringArray destructuring is the most efficient and modern way to swap variables in JavaScript. This method eliminates the need for a temporary variable.JavaScriptlet x = 5; let y = 10; [x, y] = [y, x]; 3 min read Like