I have an array:
const data = [
{location: "Phnom Penh", sale: 1000 },
{location: "Kandal", sale: 500 },
{location: "Takeo", sale: 300 },
{location: "Kompot", sale: 700 },
{location: "Prey Veng", sale: 100 },
{location: "Seam Reap", sale: 800 },
{location: "Null", sale: 0}
];
and this is my function filter:
function getSale(data, arr) {
return data
.filter(el => arr.includes(el.location))
}
arr = getSale(data, ['Phnom Penh', 'AA', 'Kompot', 'BB']);
console.log(arr);
result: [{
location: "Phnom Penh",
sale: 1000
},
{
location: "Kompot",
sale: 700
}
]
If 'AA' not found in filter I want it get the 'Null' Object.
My purpose I want the result like this:
result: [
{location: "Phnom Penh", sale: 1000},
{location: "Null", sale: 0},
{location: "Kompot", sale: 700},
{location: "Null", sale: 0}
]
How I do? Thanks for help.
You should rather use .map and .find:
const data = [
{ location: 'Phnom Penh', sale: 1000 },
{ location: 'Kandal', sale: 500 },
{ location: 'Takeo', sale: 300 },
{ location: 'Kompot', sale: 700 },
{ location: 'Prey Veng', sale: 100 },
{ location: 'Seam Reap', sale: 800 },
{ location: 'Null', sale: 0 },
];
function getSale(data, arr) {
return arr.map(el => {
const found = data.find(obj => obj.location === el);
return found ? found : { location: 'Null', sale: 0 };
});
}
arr = getSale(data, ['Phnom Penh', 'AA', 'Kompot', 'BB']);
console.log(arr);
Alternatively create a hash from data array and use .map directly:
const data = [
{ location: 'Phnom Penh', sale: 1000 },
{ location: 'Kandal', sale: 500 },
{ location: 'Takeo', sale: 300 },
{ location: 'Kompot', sale: 700 },
{ location: 'Prey Veng', sale: 100 },
{ location: 'Seam Reap', sale: 800 },
];
const hash = data.reduce((hash, obj) => {
hash[obj.location] = obj;
return hash;
}, {});
function getSale(data, arr) {
return arr.map(el => hash[el] || { location: 'Null', sale: 0 });
}
arr = getSale(data, ['Phnom Penh', 'AA', 'Kompot', 'BB']);
console.log(arr);
You could take a hash table for all locations and return either a known location or the one with Null
as location.
const
getSale = (data, locations) => {
const sales = data.reduce((r, o) => (r[o.location] = o, r), {});
return locations.map(l => sales[l] || sales.Null);
},
data = [{ location: "Phnom Penh", sale: 1000 }, { location: "Kandal", sale: 500 }, { location: "Takeo", sale: 300 }, { location: "Kompot", sale: 700 }, { location: "Prey Veng", sale: 100 }, { location: "Seam Reap", sale: 800 }, { location: "Null", sale: 0 }],
locations = ['Phnom Penh', 'AA', 'Kompot', 'BB'],
result = getSale(data, locations);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With