JavaScript 过滤方法 - 仅返回第一个对象

Mic*_*ael 1 javascript arrays sorting methods refactoring

在JavaScript中使用filter()方法,是否可以只返回第一个通过测试的实例?一旦我在汽车数组中找到第一个对象,我想将该对象从其当前位置移动到汽车数组的开头。

代码:

     cars.filter(function(car) {

        var fareType = car.data("fareType");
        var partnerCode = car.data("partnerCode");

        if (fareType == "DEAL" && partnerCode == "AV")
        {
            // get first instance only and move element to beginning of array
        }

        if (fareType == "DEAL" && partnerCode == "BU")
        {
            // also get first instance where partnerCode == BU only and move element to beginning of array 
           // If dataPrice is less than dataPrice for partner AV, move to first position, else move to second position
        }
    });
Run Code Online (Sandbox Code Playgroud)

dav*_*ave 5

我会使用.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);
    }
}
Run Code Online (Sandbox Code Playgroud)