maxspan
maxspan

Reputation: 14147

removing empty array objects from an array in javascript and react

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 }
];

Upvotes: 0

Views: 1441

Answers (4)

Nick
Nick

Reputation: 147166

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);

Upvotes: 3

Nguyễn Văn Phong
Nguyễn Văn Phong

Reputation: 14218

You should use every or some based on your requirement.

  • Use every when you want to filter value if any object having all properties is null
  • Use some when you want to filter value if any object having any property is null

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);

Upvotes: 0

hthanguyen
hthanguyen

Reputation: 96

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)

Upvotes: 0

hgb123
hgb123

Reputation: 14891

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);

Upvotes: 0

Related Questions