0
Hours
0
Minutes
0
Seconds
You need Login/Signup to run/submit the code.

How to Sort an Array of Objects by Property Values? | Frontend Problem Solving | JavaScript Interview Questions | Lodash Polyfill

@Devtools Tech
640

In this question, you must implement a function called sortBy that returns a new sorted array in ascending order by a given property. This question is similar to sortBy method provided by the Lodash library.

Syntax

sortBy(collection, property);

Arguments

  • collection (Array): The array to iterate over
  • property (String): The property based on which we need to sort

Return

  • Array: Returns a new sorted array. Does not mutate the original array.

Examples

const arrayOne = [{a: 1}, {a: 3}, {a: 2}];

// expected output: [{a: 1}, {a: 2}, {a: 3}];
sortBy(arrayOne, 'a');

const arrayTwo = [{a: 1, b: 'z'}, {a: 2, b: 'y'}, {a: 1, b: 'x'}, {a: 2, b: 'w'}];

// expected output: [{a: 1, b: 'z'}, {a: 1, b: 'x'}, {a: 2, b: 'y'}, {a: 2, b: 'w'}];
sortBy(arrayTwo, 'a');

const arrayThree = [{ a: 1, b: { c: 4 }}, { a: 2, b: { c: 2 }}, { a: 3, b: { c: 1}}, { a: 4, b: { c: 0}}];

// expected output: [{"a":4,"b":{"c":0}},{"a":3,"b":{"c":1}},{"a":2,"b":{"c":2}},{"a":1,"b":{"c":4}}]
sortBy(arrayThree, 'b.c');

Bonus

  • Once you implement the above mentioned requirements then you can extend the solution to support descending sort by passing a parameter to the function.
  • You can also extend the function to support a function rather than a property parameter. The second argument should be a function that should be invoked on each array item. The output of the function should be a boolean that decides the sort decision.

Submission

Start the timer, complete your solution, test your solution against the test cases provided by the platform, and submit it. Ideally, you should finish this question within 30-45 mins.

Share your solution with us on twitter or linkedin.

Loading IDE...