在JavaScript中使用filter()方法,是否可以仅返回通过测试的第一个实例?一旦我在汽车阵列中找到第一个物体,我想将此物体从当前位置移动到汽车阵列的开头。
代码:
#included
答案 0 :(得分:4)
我会使用.findIndex
和.splice
:
let index = cars.findIndex(function(car) {
var fareType = car.data("fareType");
var partnerCode = car.data("partnerCode");
return (fareType == "DEAL" && partnerCode == "AV");
});
if (index !== -1) {
let car = cars[index];
cars.splice(index, 1);
cars.unshift(car);
/*
* this could be reduced to:
*
* cars.unshift(...cars.splice(index, 1));
*
* at the sake of clarity
*/
}
index = cars.findIndex(function(car) {
return fareType == "DEAL" && partnerCode == "BU";
});
if (index !== -1) {
let car = cars[index];
cars.splice(index, 1);
if (car.data('price') < cars[0].data('price')) {
cars.unshift(car);
} else {
cars.splice(1, 0, car);
}
}
答案 1 :(得分:0)
您可以使用findIndex()
var selectedIndex = cars.findIndex(function(car) {
return car.data("fareType")== "DEAL" && car.data("partnerCode")== "AV";
});
if (selectedIndex > -1) {
cars = [cars[selectedIndex], ...cars.slice(0, selectedIndex), ...cars.slice(selectedIndex + 1)
}
答案 2 :(得分:0)
您可以执行以下操作:
let indexToGoFirst = 0;
cars.some((car, index) => {
const fareType = car.data('fareType');
const partnerCode = car.data('partnerCode');
if (fareType == 'DEAL' && partnerCode == 'AV') {
indexToGoFirst = index;
return True
}
})
cars[0] = cars[indexToGoFirst];
.some()
检查数组中的任何内容是否与条件匹配,并在满足条件时停止循环,因此您可以使用它来设置第一个元素。
答案 3 :(得分:0)
查找索引并使用元素
创建新数组var index = cars.findIndex(function(car) {
var fareType = car.data("fareType");
var partnerCode = car.data("partnerCode");
// get first instance only and move element to beginning of array
return fareType == "DEAL" && partnerCode == "AV";
});
var newCars = index > 0? [cars[index]].concat(cars.slice(0, index)).concat(cars.slice(index + 1): cars;