用字符串和数字过滤数组的最干净的方法



我想知道哪种方法是过滤一个由字符串和数字混合的数组的最干净的方法,以根据函数的参数获得最佳结果。

我有这个阵列

const vehicles = [{
Brand: 'Peugeot',
Type: 'Car',
Modelo: '206',
Puertas: 4,
Precio: 200000
},
{
Brand: 'Honda',
Type: 'Motorcycle',
Modelo: 'Titan',
Cilindrada: '125cc',
Precio: 60000
},{
Brand: 'Peugeot',
Type: 'Car',
Modelo: '208',
Puertas: 5,
Precio: 250000
},{
Brand: 'Yamaha',
Type: 'Motorcycle',
Modelo: 'YBR',
Cilindrada: '160cc',
Precio: 80500
}]

例如,当我搜索"y"时,我想要函数返回

{
Brand: 'Yamaha',
Type: 'Motorcycle',
Modelo: 'YBR',
Cilindrada: '160cc',
Precio: 80500
}

我的第一个方法是这个功能

function filterByValue(array, value) {
return array.filter((data) =>  JSON.stringify(data).toLowerCase().indexOf(value.toLowerCase()) !== -1);
}

但它返回了整个vehicles阵列

您可以搜索值,这些值在转换为字符串时包含要搜索的子字符串:

const vehicles = [{
Brand: 'Peugeot',
Type: 'Car',
Modelo: '206',
Puertas: 4,
Precio: 200000
},
{
Brand: 'Honda',
Type: 'Motorcycle',
Modelo: 'Titan',
Cilindrada: '125cc',
Precio: 60000
},{
Brand: 'Peugeot',
Type: 'Car',
Modelo: '208',
Puertas: 5,
Precio: 250000
},{
Brand: 'Yamaha',
Type: 'Motorcycle',
Modelo: 'YBR',
Cilindrada: '160cc',
Precio: 80500
}];
const input = 'y'.toLowerCase();
console.log(
vehicles.filter(
vehicle => Object.values(vehicle).some(
val => String(val).toLowerCase().includes(input)
)
)
);

如果你想更有趣,你可以对子字符串出现次数最多的结果进行排序,或者对从输入开始的值赋予额外的权重,或者根据与输入的Levenstein距离进行排序。

以下实现使用JSON.stringify逻辑,但仅将其应用于每个对象中的values

const vehicles = [
{
Brand: "Peugeot",
Type: "Car",
Modelo: "206",
Puertas: 4,
Precio: 200000,
},
{
Brand: "Honda",
Type: "Motorcycle",
Modelo: "Titan",
Cilindrada: "125cc",
Precio: 60000,
},
{
Brand: "Peugeot",
Type: "Car",
Modelo: "208",
Puertas: 5,
Precio: 250000,
},
{
Brand: "Yamaha",
Type: "Motorcycle",
Modelo: "YBR",
Cilindrada: "160cc",
Precio: 80500,
},
];
function filterByValue(array, value) {
return array.filter(
(data) =>
JSON.stringify(Object.values(data))
.toLowerCase()
.indexOf(value.toLowerCase()) !== -1
);
}
console.log(filterByValue(vehicles, "y"));

这将只在数组中对象的属性值中检查value

const vehicles = [{
Brand: 'Peugeot',
Type: 'Car',
Modelo: '206',
Puertas: 4,
Precio: 200000
},
{
Brand: 'Honda',
Type: 'Motorcycle',
Modelo: 'Titan',
Cilindrada: '125cc',
Precio: 60000
}, {
Brand: 'Peugeot',
Type: 'Car',
Modelo: '208',
Puertas: 5,
Precio: 250000
}, {
Brand: 'Yamaha',
Type: 'Motorcycle',
Modelo: 'YBR',
Cilindrada: '160cc',
Precio: 80500
}
]

const filterByValue = (array, value) => {
return array.filter((data) =>
Object.values(data).some((val) =>
val.toString().toLowerCase().includes(value.toLowerCase()),
)
)
}
console.log(filterByValue(vehicles, 'y'));

最新更新