-2

Let's say we have an array of objects called result:

{ "name": "C:\\file.json", "relevance": 0.5 }

{ "name": "C:\\folder", "relevance": 0.5454545454545454 }

{ "name": "C:\\file_1.txt", "relevance": 0.1 }

How do we sort it by relevance key and push the name values into a new array in the sorted order, so that we get the following arr:

["C:\\folder", "C:\\file.json", "C:\\file_1.txt"]

UPDATE

It's not a duplicate! I don't know why people in js threads always marking answers as duplicate, even when they very much aren't

Un1
  • 3,874
  • 12
  • 37
  • 79
  • what is actually the specific problem by using [`Array#sort`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) and later with [`Array#map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)? – Nina Scholz May 29 '18 at 14:28
  • @NinaScholz I'm not sure how to do it – Un1 May 29 '18 at 14:28

1 Answers1

3

You can do it like this;

var result = [ { "name": "C:\\file.json", "relevance": 0.5 }, { "name": "C:\\folder", "relevance": 0.5454545454545454 }, { "name": "C:\\file_1.txt", "relevance": 0.1 } ]
var newArray = result.sort((a, b) => parseFloat(b.relevance) - parseFloat(a.relevance)).map(item => item.name);
console.log(newArray);
lucky
  • 12,734
  • 4
  • 24
  • 46
  • hmm, It puts `name` item with the relevance `0.5454545454545454` after the `name` item with relevance `0.5` even though the latter one is smaller. How can I apply `toFixed(1)` in the process and only sort them after that? – Un1 May 29 '18 at 14:35
  • @Un1 Don't use `.toFixed`, which produces a string. Instead, compare `Math.round(a.relevance * 10)` – Bergi May 29 '18 at 14:41
  • I updated the answer. Would you try it again ? – lucky May 29 '18 at 14:41
  • @lucky I just did, it seems like it puts them into the array in random order. It puts `0.7` after `0.6666666666666666` even thought it's bigger, I don't know why – Un1 May 29 '18 at 14:50
  • Would you try it again ? – lucky May 29 '18 at 14:53
  • 1
    @lucky thank you very much kind sir, that works! – Un1 May 29 '18 at 14:56