I am trying to remove empty array object from my array. I have tried filter method but wont work as my array is complex one.
const input =
[
{ daysIn: 1, daysOut: 1, category: "Day Shift" },
{ daysIn: 1, daysOut: 1, category: "Day Shift" },
{ daysIn: null, daysOut: null, category: null }
];
-
What defines an "empty array object"? It's not obvious from your sample data. What is your expected output?Nick– Nick2021年02月04日 07:06:27 +00:00Commented Feb 4, 2021 at 7:06
-
my bad just updated the questionmaxspan– maxspan2021年02月04日 07:09:40 +00:00Commented Feb 4, 2021 at 7:09
-
What have you tried so far? What the expected result do you want?Nguyễn Văn Phong– Nguyễn Văn Phong2021年02月04日 07:19:06 +00:00Commented Feb 4, 2021 at 7:19
4 Answers 4
You could use Array.filter with Array.some to include any object which has any non-null value:
const data = [{ daysIn: 1, daysOut: 1, category: "Day Shift" },{ daysIn: 1, daysOut: 1, category: "Day Shift" },{ daysIn: null, daysOut: null, category: null }];
const result = data.filter(o => Object.values(o).some(v => v !== null));
console.log(result);
2 Comments
every or some. LOLsome removes the need to negate the result, so it makes it easier to read IMO.You could use filter and every
Approach here is ot reject every objects that have the all falsy values
x == null will return true for x of null/undefined
const data = [
{ daysIn: 1, daysOut: 1, category: "Day Shift" },
{ daysIn: 1, daysOut: 1, category: "Day Shift" },
{ daysIn: null, daysOut: null, category: null },
{}
];
const res = data.filter((d) => !Object.values(d).every((v) => v == null));
console.log(res);
Comments
You can check length of object to determine it's empty or not.
Update solution:
const data = [
{ daysIn: 1, daysOut: 1, category: "Day Shift" },
{ daysIn: 1, daysOut: 1, category: "Day Shift" },
{ daysIn: null, daysOut: null, category: null }];
const filterEmptyObject = data => data.filter(obj => Object.values(obj).every(o => {
if(!o) {
// this will also check for undefined, empty string, 0, false, NaN.
return false;
}
return true;
}));
const filteredData = filterEmptyObject(data);
console.log(filteredData)
Comments
You should use every or some based on your requirement.
- Use
everywhen you want to filter value if any object having all properties isnull - Use
somewhen you want to filter value if any object having any property isnull
In your case "remove empty array object", I decided use every.
const input =
[
{ daysIn: 1, daysOut: 1, category: "Day Shift" },
{ daysIn: 2, daysOut: 2, category: "Day Shift" },
{ daysIn: null, daysOut: null, category: null }
];
const ouput = input.filter(r => Object.values(r).every(c => c !== null));
console.log(ouput);