I have this array of objects:
[
{name: "John", surname: "Doe", car: "BWM"},
{name: "Louis", surname: "Vuitton", car: "MERCEDES"},
{name: "Bob", surname: "Ross", car: "FORD"},
{name: "Dylan", surname: "James", car: "FERRARI"},
{name: "Damien", surname: "Rivers", car: "JAGUAR"},
]
And I have this code
return this._object.filter(object => object.car === params1 && object.car === params2 && object.car=== params3)
params can be what ever brand car, but they are optional besides params1, user can provide only params1 and let the other two undefined.
Params are selected by the user on a select html option, he can choose up to 3 car brand, so 3 params and i pass it as url parameters and pass these parameters to my function
I want to do something like in one line : if params2 and params3 exists don't change the code snippet, if they don't exist, only do the filter on params1
Example 1: if params1 = BMW and params 2-3 = undefined
it would return this object {name: "John", surname: "Doe", car: "BWM"}
Example 2: if params1 = BMW, params2 = MERCEDES
it would return this result :
{name: "John", surname: "Doe", car: "BWM"}
{name: "Louis", surname: "Vuitton", car: "MERCEDES"},`
Same concept with params 3 == FERRARI
I can't see how I can do that with few lines/one line, besides doing if statement everywhere
Thanks !
you can do something like this
const filterData = (data, ...params) => data.filter(d => params.includes(d.car))
const data = [{name: "John", surname: "Doe", car: "BMW"},
{name: "Louis", surname: "Vuitton", car: "MERCEDES"},
{name: "Bob", surname: "Ross", car: "FORD"},
{name: "Dylan", surname: "James", car: "FERRARI"},
{name: "Damien", surname: "Rivers", car: "JAGUAR"},]
console.log(filterData(data, 'BMW'))
console.log(filterData(data, 'BMW', 'MERCEDES'))
You can make the code even more flexible. Instead of passing 3 different params, pass an array like below.
let cars = ["BMW", "MERCEDES"];
now you can check it using javascript's includes method.
return this._object.filter(object => cars.includes(object.car))
By using Array.prototype.includes() you can check against a number of target expressions. It will return true if the argument is equal to at least one element of the array.
In an initial args.map() loop I make sure that the input values are all upper case.
const data=[{name: "John", surname: "Doe", car: "BMW"},
{name: "Louis", surname: "Vuitton", car: "MERCEDES"},
{name: "Bob", surname: "Ross", car: "FORD"},
{name: "Dylan", surname: "James", car: "FERRARI"},
{name: "Damien", surname: "Rivers", car: "JAGUAR"}];
function filt(...args){
args=args.map(a=>a.toUpperCase());
return data.filter(d=>
args.includes(d.car))
}
console.log(filt("BMW","Mercedes"));
console.log(filt("jaguar"))