I have an array of objects. I want to loop trough that array and to check if an item match a criteria, using reduce method from javascript:
const arr = [{
value: 'test',
label: 'Test'
},
{
value: 'car',
label: 'Car'
},
]
const res = arr.reduce((acc, item) => {
if (item.value) {
acc.push({
element: item.label,
id: item.value,
})
}
if(item.value !== 'car') {
acc.push({element: 'here', id: 'here'})
}
return acc
}, [])
console.log(res)
Using if(item.value !== 'car') { acc.push({element: 'here', id: 'here'}) } i try to inspect if in my list is not at all a value that is not equal with 'car', then add that object, but it adds even if in the list exists car title, but what i want to achieve is to see if in the array is not any item that is equal with car, only after that to add that object. How to achieve that without using find() but only reduce()?
Examples: 1. if i check the title car then that object should not be added . 2. If i check the title 'unknown', then that object should be added.
As I understood you only need to filter by some elements (not car elements). This way, you don't need to use "reducer", you can use "filter". Please, check the code below:
const arr = [{
value: 'test',
label: 'Test'
},
{
value: 'car',
label: 'Car'
},
];
// Using filter (recommended in your case)
// const notCarElements = arr.filter(elem => elem.value !== 'car');
// Using reducer
const notCarElements = arr.reduce((acc, item) => {
if (item.value === 'car') return acc;
acc.push(item);
return acc;
}, []);
console.log(notCarElements);