什么是numpy argsort的javascript等价物?

时间:2017-10-07 16:26:48

标签: javascript numpy

我想通过点击计数对imgUrl数组进行排序。我有两个阵列。

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

在numpy中很容易。我使用order = np.argsort(clickCount)然后创建另一个数组newArray = [imgUrl[i] for i in order]

如何在javascript(最好是vanilla)中实现相同的效果?

3 个答案:

答案 0 :(得分:8)

你可以在python中使用Schwartzian transform也称为Decorate-Sort-Undecorate(DSU)。

<强> DSU:

  1. 装饰 - 使用Array#Map使用所需的排序数据来丰富数组中的每个项目
  2. 排序 - 使用添加的数据排序
  3. Undocrate - 再次使用Array #map提取已排序的数据
  4. <强>演示:

    &#13;
    &#13;
    const clickCount = [5,2,4,3,1];
    const imgUrl = ['1.jpg','2.jpg','3.jpg','4.jpg','5.jpg'];
    
    const result = imgUrl
      .map((item, index) => [clickCount[index], item]) // add the clickCount to sort by
      .sort(([count1], [count2]) => count2 - count1) // sort by the clickCount data
      .map(([, item]) => item); // extract the sorted items
      
    console.log(result);
    &#13;
    &#13;
    &#13;

答案 1 :(得分:1)

为了完整起见,这是我对实际答案的解决方案(提供 argsort 函数),通过使用 DSU 扩展 Ori 的答案。 由于排序默认采用第一个元素,因此将其实现为 DSU 只是添加一个索引,对其进行排序,然后采用索引。

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

答案 2 :(得分:0)

函数方法(例如@Ori Drori的代码)总是很吸引人,但是在这种情况下,您只需要重新排列数组的项即可。我相信这是一种更简单的方法,而且代码也更容易阅读。

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

sortByArrayRefOrder = (data, orderRefArr) => {
	let orderedArr = [], i=0;
	orderRefArr.map( o => { orderedArr[o-1] = data[i++]});
	return orderedArr.reverse();
}

console.log ( sortByArrayRefOrder(imgUrl, clickCount) );