JavaScript实现数组首尾对应位置元素及对象属性比较
数组对称位置对象元素比较筛选实现
需求说明:
- 将数组中对称位置的元素配对比较:第1个与最后1个、第2个与倒数第2个……直到数组中间位置
- 比较规则:
- 优先比较对象的
note属性,取note值更大的元素加入结果数组 - 若
note属性相等,则比较year属性,取year值更大的元素加入结果数组
- 优先比较对象的
实现代码
function compare(arr) { const n = arr.length const mid = Math.floor(n / 2) const second = []; for (let i = 0; i < mid; i++) { if (arr[i].note === arr[n - i - 1].note) { if (arr[i].year > arr[n - i - 1].year) { second.push(arr[i]) } else { second.push(arr[n - i - 1]) } } else if (arr[i].note > arr[n - i - 1].note) { second.push(arr[i]) } else { second.push(arr[n - i - 1]) } } return second }
内容的提问来源于stack exchange,提问作者Cyro Alves
相关产品推荐
相关产品推荐

