Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

213
Views
How to order by ascending and descending JSON with a condition in lodash or javascript

I want to sort by ascending and descending order of the array of object below using javascript or lodash. The conditions are below:

  1. This array will have objects with duplicate id
  2. I want to sort the array based on 'name' and get the unique 'number' fields in an array based on the 'name' sort with a specific 'id'.

This is the data.

var data = [
  { id: 1, age: 36, name: 'ram', number: 11},
  { id: 2,  age: 40, name: 'sam', number: 11 },
  { id: 3, age: 37, name: 'roy', number: 11 },
  { id: 1, age: 41, name: 'fil', number: 12 },
  { id: 2,  age: 43, name: 'joy', number: 12 },
  { id: 3, age: 46, name: 'john', number: 12 }
]

Expected output when sorting based on name when id='1' and in ascending order:

[12,11]

Expected output when sorting based on name when id='2' and in descending order:

[11,12]
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You need to split up your problem:

  1. filter the array on id === x;
  2. sort the resulting array;
  3. map the resulting values so you only extract the number:

var data = [
  { id: 1, age: 36, name: 'ram', number: 11},
  { id: 2,  age: 40, name: 'sam', number: 11 },
  { id: 3, age: 37, name: 'roy', number: 11 },
  { id: 1, age: 41, name: 'fil', number: 12 },
  { id: 2,  age: 43, name: 'joy', number: 12 },
  { id: 3, age: 46, name: 'john', number: 12 }
]

const id = 1;
const result = data
  .filter(row => row.id === id)
  .sort((a, b) => a.name.localeCompare(b.name))
  .map(row => row.number);
  
console.log(result);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!