Sort Object Array Based On Another Array Of Keys - Javascript

Sort Object Array Based On Another Array Of Keys - Javascript

5 min read Jun 20, 2024
Sort Object Array Based On Another Array Of Keys - Javascript

Sort Object Array Based on Another Array of Keys - JavaScript

This article will guide you on how to sort an array of objects in JavaScript based on another array of keys. This technique is useful when you need to rearrange objects according to a specific order determined by the key array.

Let's break down the process:

Understanding the Scenario

Imagine you have an array of objects representing products, each with properties like name, price, and category. You also have a separate array of keys representing the desired order for sorting the products.

Example Data:

const products = [
  { name: 'Laptop', price: 1000, category: 'Electronics' },
  { name: 'T-shirt', price: 20, category: 'Clothing' },
  { name: 'Headphones', price: 150, category: 'Electronics' },
  { name: 'Shoes', price: 80, category: 'Clothing' }
];

const sortKeys = ['category', 'price'];

In this scenario, we want to sort the products array first by category and then by price as defined in the sortKeys array.

Sorting Implementation

Here's a JavaScript function that takes an array of objects and a key array as input and returns a sorted array:

function sortObjects(objects, keys) {
  return objects.sort((a, b) => {
    for (let i = 0; i < keys.length; i++) {
      const key = keys[i];
      if (a[key] < b[key]) return -1;
      if (a[key] > b[key]) return 1;
    }
    return 0; // If all keys are equal, keep original order
  });
}

Explanation:

  1. sortObjects(objects, keys): This function takes the object array (objects) and the key array (keys) as arguments.
  2. objects.sort((a, b) => ...): This uses the built-in sort method for arrays. The callback function ((a, b) => ...) compares two objects (a and b) and determines their relative order.
  3. for (let i = 0; i < keys.length; i++) { ... }: This loop iterates through each key in the sortKeys array.
  4. const key = keys[i];: Retrieves the current key from the sortKeys array.
  5. if (a[key] < b[key]) return -1; and if (a[key] > b[key]) return 1;: These lines compare the values of the current key in both objects. If a is less than b, it returns -1 (meaning a should come before b), and vice versa.
  6. return 0;: If all keys are equal, the original order is maintained.

Applying the Function

const sortedProducts = sortObjects(products, sortKeys);

console.log(sortedProducts); 

Output:

[
  { name: 'T-shirt', price: 20, category: 'Clothing' },
  { name: 'Shoes', price: 80, category: 'Clothing' },
  { name: 'Headphones', price: 150, category: 'Electronics' },
  { name: 'Laptop', price: 1000, category: 'Electronics' }
]

The output demonstrates that the products array is now sorted first by category (Clothing before Electronics) and then by price within each category.

Conclusion

Sorting an object array based on another array of keys is a common task in JavaScript development. Using the provided function and understanding its logic, you can effectively rearrange your object data according to specific ordering rules. This technique can be applied to various scenarios where you need to control the order of data based on multiple criteria.