JavaScript 数组排名 - JavaScript
假如有三个这样的 JavaScript 数组,其中包含如下数字 −
const array1 = [10,23,53,74,33,56,6,0,43,45,11]; const array2 = [52,46,27,28,4,11,53,6,75,75,22]; const array3 = [26,18,10,12,31,12,5,8,44,34,65];
所有数组的长度始终相同。
我们要求编写一个 JavaScript 函数,该函数在一个现有数组中将任意数量此类数组的对应元素按照元素的排名(即以递减方式排序)映射起来。
因此,对于上述数组,输出应如下所示 −
const array1= [3,2,1,1,1,1,2,3,2,2,3]; const array2= [1,1,2,2,2,2,1,2,1,1,2]; const array3= [2,3,3,3,3,3,3,1,2,3,1];
示例
以下为代码 −
const array1 = [10,23,53,74,33,56,6,0,43,45,11]; const array2 = [52,46,27,28,4,11,53,6,75,75,22]; const array3 = [26,18,10,12,31,12,5,8,44,34,65]; const transpose = (rank, arr) => { return arr.map((el, ind) => { return [...(rank[ind] || []), el]; }); }; const ranks = arr => { return arr.map( Map.prototype.get, [...arr] .sort((a, b) => b - a) .reduce((r => (m, v) => m.set(v, (r++, m.get(v)) || r))(0), new Map) ); }; const findRanks = (...arrs) => { return arrs .reduce(transpose, []) .map(ranks) .reduce(transpose, []); }; console.log(findRanks(array1, array2, array3));
输出
这将在控制台上生成以下输出 −
[ [ 3, 2, 1, 1, 1, 1, 2, 3, 3, 2, 3 ], [ 1, 1, 2, 2, 3, 3, 1, 2, 1, 1, 2 ], [ 2, 3, 3, 3, 2, 2, 3, 1, 2, 3, 1 ] ]
广告