Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the javascript equivalent of numpy argsort?

I want to sort the imgUrl array by click count. I have two arrays.

clickCount = [5,2,4,3,1]
imgUrl     = ['1.jpg','2.jpg','3.jpg','4.jpg','5.jpg']

In numpy it is easy. I use order = np.argsort(clickCount) then I create another array newArray = [imgUrl[i] for i in order].

How do I achieve the same effect in javascript (preferably vanilla)?

like image 310
Souradeep Nanda Avatar asked Oct 07 '17 16:10

Souradeep Nanda


People also ask

Is there a Numpy equivalent in JavaScript?

jsnumpy. It provides equivalent of Numpy in JavaScript. All functions works on ndArray also.

What is Numpy Argsort?

numpy.argsort() function is used to perform an indirect sort along the given axis using the algorithm specified by the kind keyword. It returns an array of indices of the same shape as arr that would sort the array. It means indices of value arranged in ascending order.

What is the difference between Argsort and sort?

sort() returns the sorted array whereas np. argsort() returns an array of the corresponding indices. The figure shows how the algorithm transforms an unsorted array [10, 6, 8, 2, 5, 4, 9, 1] into a sorted array [1, 2, 4, 5, 6, 8, 9, 10] .

How do you reverse NP Argsort?

Use list slicing to use NumPy argsort in descending order. Use numpy. argsort(an_array) to sort the indices of an_array in ascending order. Use the syntax ranked[::-1] with ranked as the previous result to reverse ranked .


1 Answers

For completeness, here's my solution to the actual answer (providing argsort function), by expanding on Ori's answer with DSU. Since sort is by default taking the first element, so implementing it as DSU is merely adding an index, sorting it, then taking the indices.

let decor = (v, i) => [v, i];          // set index to value
let undecor = a => a[1];               // leave only index
let argsort = arr => arr.map(decor).sort().map(undecor);

clickCount = [5, 2, 4, 3, 1]
imgUrl = ['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg']

order = argsort(clickCount);
newArray = order.map(i => imgUrl[i])

console.log(newArray);
like image 84
Eran W Avatar answered Oct 26 '22 22:10

Eran W