-2

help me pls
Object = [{"name":A,"val":20}, {"name":B,"val":7}, {"name":C,"val":20}, {"name":D,"val":8}, {"name":E,"val":5}]

SortedValue = [20, 20, 7, 8, 5]

i want like this --> Sorted_name = [A,C,D,B,E] or Sorted_name = [C,A,D,B,E]

  • Welcome to SO. You might find reading the site [help section](https://stackoverflow.com/help) useful when it comes to [asking a good question](https://stackoverflow.com/help/how-to-ask), and this [question checklist](https://meta.stackoverflow.com/questions/260648/stack-overflow-question-checklist). Code that you've worked on to solve the problem should include a [mcve]. – Andy Jul 07 '21 at 10:24
  • You mean you want the val in reverse numerical order? – mplungjan Jul 07 '21 at 10:26
  • IIUC, you want to sort the array based on the count for each `val`? – adiga Jul 07 '21 at 10:29
  • Should be `Sorted_name = [A,C,B,D,E] or Sorted_name = [C,A,B,D,E]` right? – Giovanni Esposito Jul 07 '21 at 10:41

3 Answers3

1

Simple forEach on SortedValuewith a find on Obj array like:

let Obj = [{"name":"A","val":20}, {"name":"B","val":7}, {"name":"C","val":20}, {"name":"D","val":8} , {"name":"E","val":5}]

let SortedValue = [20, 20, 7, 8, 5];
let result = [];

SortedValue.forEach(x => {
   let findObj = Obj.find(y => y.val === x);
   if (findObj) {
      result.push(findObj.name);
      Obj.splice(Obj.map(z => z.name).indexOf(findObj.name), 1); 
   }
});

console.log(result);
Giovanni Esposito
  • 10,696
  • 1
  • 14
  • 30
0

I would use both sort and map functions

values = [{"name":"A","val":20}, {"name":"B","val":7}, {"name":"C","val":20}, {"name":"D","val":8}, {"name":"E","val":5}]

const sorted_names = values.sort((a,b) => b.val - a.val).map(item => item.name)

console.log(sorted_names)
RenaudC5
  • 3,553
  • 1
  • 11
  • 29
0

Here are some ways using sort.

const object = [{name:"A", val: 20}, {name: "E", val: 7}, {name: "D", val: 20}, {name:"C",val:8}, {name:"B",val:5}];

const nameSort = object.sort((a, b)=> { 
    if (a.name > b.name) return 1;
    if (a.name < b.name) return -1;
    return 0;
}).map(item => item.name);
console.log('nameSort: ', nameSort);


const nameSortSimplified = object.sort((a, b)=> a.name < b.name ? -1 : a.name > b.name ? 1 : 0).map(item => item.name);
console.log('name sort simplified: ', nameSortSimplified);

const valSort = object.sort((a, b)=> a.val - b.val).map(item => item.name);
console.log('val sort: ', valSort);