假设我们有三个Number的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 ] ]