简体   繁体   中英

Sort Object Elements in Javascript

I have an object like this:

 {
  "name":['John','Bob','Ram','Shyam'],
  "marks":['64','22','80','32']
 }

I have to sort the names. After I sort names, marks must be matched according to the names.

When I use sort() function, It only sorts the names. How can I sort my overall object?

One option is to alter your data structure to be more sortable. For example:

 const data = { names: ['John','Bob','Ram','Shyam'], marks: ['64','22','80','32'] } const people = data.names.map((name, i) => ({ name, mark: data.marks[i] })) const sorted = people.sort((a, b) => a.name.localeCompare(b.name)) console.log(sorted)

A second option would be to keep an array of indexes, which you sort based on the data. This doesn't alter your original structures, but I don't think it is a good option, because it would be hard to keep both the names and marks arrays synced. For example:

 const data = { names: ['John','Bob','Ram','Shyam'], marks: ['64','22','80','32'] } const index = Array.from(Array(data.names.length).keys()) index.sort((a, b) => data.names[a].localeCompare(data.names[b])) console.log(index) // use the names & marks index.forEach(i => { console.log(`${data.names[i]} - ${data.marks[i]}`) })

You can create another key by name rel and its value will be an array of objects , where each object has keys by name name & mark .

While creating this array you can use sort function to sort these objects in order

 let obj = { "name": ['John', 'Bob', 'Ram', 'Shyam'], "marks": ['64', '22', '80', '32'] } obj.rel = obj.name.map(function(e, i) { return { name: e, mark: obj.marks[i] } }).sort((a, b) => a.name.localeCompare(b.name)) console.log(obj)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM