this is not a duplicate. please see my comment below!
does somebody knows an more efficient solution than for loops in ES6?
I have written the following, which lacks of performance. Any improvement ideas? Highly appreciated.
Basically i have an object regarding cars and an array about user preferences. Expected behavior is to push all relevant car names into an array.
Users can give any amount of preferences. A car name should be only pushed, if ALL specifications are mentioned in preferences. Therefore some preferences will be "leftovers".
For that reason in the following example Honda appears, but not BMW, which is the expected (but very slow behavior).
// Car objects
const cars = [{
name: "Honda",
category: "eco",
specs: {
0: "green",
1: "fast",
2: "automatic"
}
},
{
name: "BMW",
category: "sport",
specs: {
0: "blue",
1: "fast",
2: "automatic"
}
}
]
// User preferences
const preferences = ["green", "fast", "4x4", "automatic", "panorama"]
// function to get length/amount of car specifications
function objsize(Myobj) {
var osize = 0,
key;
for (key in Myobj) {
if (Myobj.hasOwnProperty(key)) osize++;
}
return Object(osize);
};
//function to check if ALL specifications are included in the user preferences
function checkSpecs(spec_item) {
return preferences.includes(spec_item)
}
// main function
function filter_func() {
//final results
let matched_cars = []
for (i = 0; i < objsize(cars); i++) {
let specs_collector = []
for (j = 0; j < objsize(cars[i].specs); j++) {
specs_collector.push(cars[i].specs[j])
}
if (specs_collector.every(checkSpecs) === true) {
matched_cars.push(cars[i].name)
specs_collector = []
}
}
console.log(matched_cars)
}
filter_func()