在 JavaScript 中最大化第一个数组而不是第二个
问题
我们需要编写一个JavaScript函数,该函数接受两个相同长度的数字数组arr1和arr2。
我们的函数应该打乱第一个数组arr1的元素,使其最大元素数大于数组arr2的对应元素。然后该函数应返回混洗后的数组。
例如,如果函数的输入是
输入
const arr1 = [3, 5, 12, 19]; const arr2 = [2, 9, 3, 12];
输出
const output = [3, 12, 5, 19];
输出说明
在shufflearr1之前,它有3个对应元素比arr2大,但在shuffled数组中,4个元素都更大。
以下是代码:
示例
const arr1 = [3, 5, 12, 19];
const arr2 = [2, 9, 3, 12];
const maximiseArray = (arr1 = [], arr2 = []) => {
arr1.sort((a, b) => b - a)
const indexes = arr2.map((v, index) => index).sort((a, b) => arr2[b] - arr2[a])
const res = []
for(let i = 0; i < indexes.length; i++) {
const index = indexes[i]
res[index] = arr1[0] > arr2[index] ? arr1.shift() : arr1.pop()
}
return res
}
console.log(maximiseArray(arr1, arr2));输出结果[ 3, 12, 5, 19 ]
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下