I have an array of objects:
const breeds=[{name: 'Golden', temperament: ['friendly', 'kind', 'smart']},{name: 'Husky', temperament: ['alert', 'loyal', 'gentle']},{name: 'Yorkshire Terrier', temperament: ['bold', 'independent', 'kind']}]
I would like to sort them by selected "temperament." Let's say a user has selected both "kind" & "friendly", it should only return "Golden".
I'm using javascript and underscore and this is what I have tried so far:
//selected is an array of selected temperaments
//breeds is the array of objects
function filterTemperaments(selected, breeds) {
return _.filter(breeds, function (breed) {
if (!breed.temperament) breed.temperament = "";
const breedList = breed.temperament;
return breedList.includes(...selected);
}, selected);
}
This seems to only be returning breeds that match the first temperament in the selected array. For example if selected is ['kind', 'loyal']
and the breed is {name:'Golden', temperament: ['kind', 'smelly']}
, Golden will still come back as true, despite not matching the "Loyal" temperament
Any thoughts for a better solution here? Thanks in advance!!
You can use filter
to return only those breeds which have every
temperament selected
const breeds=[{name: 'Golden', temperament: ['friendly', 'kind', 'smart']},{name: 'Husky', temperament: ['alert', 'loyal', 'gentle']},{name: 'Yorkshire Terrier', temperament: ['bold', 'independent', 'kind']}], selected = ['kind', 'friendly'] const filtered = breeds.filter(b => selected.every(s => b.temperament.includes(s))) console.log(filtered)
it is easy to use using filter
and every
in order to know if you got any matches and return the matched values.
const breeds = [{ name: 'Golden', temperament: ['friendly', 'kind', 'smart'] }, { name: 'Husky', temperament: ['alert', 'loyal', 'gentle'] }, { name: 'Yorkshire Terrier', temperament: ['bold', 'independent', 'kind'] }] //selected is an array of selected temperaments //breeds is the array of objects function filterTemperaments(selected, breeds) { return breeds.filter(({ temperament }) => { //here I'm desctructuring the object only to get the temperaments. return selected.every(selection => temperament.indexOf(selection) !== -1) }) } const result = filterTemperaments(['kind', 'friendly'], breeds); console.log(result)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.