const arrFilter = [{id:1},[],[]];
how can I filter the empty array in the above example, so that the result would be the object with an id only
>Solution :
You can use the length of the array returned from Object.keys() to determine if objects, arrays or strings are empty however it won’t work on numbers.
With that in mind, try this assuming that
- all empty objects, arrays and strings should be omitted
- everything else stays
const arrFilter = [{id:1},[],[], "a string", "", 1, 0];
const nonEmpties = arrFilter.filter(
(item) => typeof item === "number" || Object.keys(item).length > 0
);
console.log(nonEmpties);