-3

I have an array of object like this

let arr = [{
 user: 1,
 details: 'sample' },
{
 user: null,
 details: 'sample' },
{
 user: 3,
 details: 'sample' }];

I want to filter out the null user. But when I tried to map the array I get this result.

[user1, [], user3]

I want to get rid of the [] so I can get the correct data and length. How can I achieve this in Javascript?

sonEtLumiere
  • 4,461
  • 3
  • 8
  • 35

7 Answers7

4

You can try this, the condition inside the filter will check if user inside each item is a truthy value or not. So added advantage is you can remove out users having user as undefined or "" or null from the original array

  const users = [
    { user: 1, details: "sample" },
    {user: null, details: "sample"},
    {user: 3, details: "sample"}
  ];

const result = users.filter((item) => item.user);
console.log(result);
CodeNinja
  • 41
  • 3
2
const users = 
    [{
      user: 1,
      details: 'sample' },
    {
      user: null,
     details: 'sample' },
    {
     user: 3,
     details: 'sample' 
    }]

Easiest way:

const newUsers = users.filter(item => item.user)

Predrag Davidovic
  • 1,411
  • 1
  • 17
  • 20
1

Below snippets are from w3docs.

To remove empty elements from a JavaScript Array, the filter() method can be used, which will return a new array with the elements passing the criteria of the callback function.

The filter() method creates an array filled with all array elements that pass a test. To remove null or undefined values do the following:

const array = [0, null, 1, "", 2, undefined, 2, , , , , 4, , 4, , 5, , 6, , , , ];
const arrFiltered = array.filter(el => {
  return el != null && el != '';
});
console.log(arrFiltered);
Prabesh Gouli
  • 413
  • 3
  • 11
0
 const data = ["user1", [], "user3"];
 const res = data.filter(
        (item) => item !== Array.isArray(item) && item.length
      );
 console.log(res);

First check if your element is an array Array.isArray(item) and then check if you array has length, if no it means it is an empty and we can filter it.

Anna Vlasenko
  • 916
  • 5
  • 8
0

You can use filter like that,

  yourArr = yourArr.filter(element => element.user != null);

see the attached image it contains the answer

example for using array filter method in javascript

Emad Abdou
  • 277
  • 1
  • 7
0

I hope this will help you.

var arr = [{ user: 1, details: 'sample' }, { user: null, details: 'sample' }, { user: 3, details: 'sample' }];
var result = arr2.filter(el => el.user !== null);
-1

You can use:

var newArray = array.filter(value => Object.keys(value).length !== 0);
Prabesh Gouli
  • 413
  • 3
  • 11
  • Downvoted becuase if you use the `const array = [0, null, 1, "", 2, undefined, 2, , , , , 4, , 4, , 5, , 6, , , , ];` from https://stackoverflow.com/a/62977205/446954 above, this function raises a `Uncaught TypeError: Cannot convert undefined or null to object` exception. – webdevguy Sep 14 '22 at 19:45