[Vuejs]-I want to sort Data by duplicate data in array [Javascript in vue]

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)

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);

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);

Leave a comment