C Sharper
C Sharper

Reputation: 8626

Javascript : Check if any of the element in array is null or empty (Return True-False)

I have below array in javascript -

[
{
 id:1,
 deptName:"Cashier"
},
{
 id:2,
 deptName:"MF"
},
{
 id:3,
 deptName:""
},
{
 id:4,
 deptName:"RD"
},
{
 id:5,
 deptName:null
},
]

I want to check if any element for deptName in above array is null or empty.

I used -

var isNullOrEmpty= data.every(ele=>(ele.deptName===null || ele.deptName==="")) 

use of every function is returning false in every case. i.e. whether I keep deptName in any of the element to be null / empty or I fill it with value. With both the cases it is returning me false.

I want to check if any of the deptName in array is null or empty.

Upvotes: 2

Views: 2063

Answers (2)

zahra zamani
zahra zamani

Reputation: 1375

every() method in JavaScript is used to checks whether all the elements of the array satisfy the given condition or not. The Array. some() method in JavaScript is used to check whether at least one of the elements of the array satisfies the given condition or not.
For your issue:

var isNullOrEmpty= data.some(ele=>(ele.deptName===null || ele.deptName===""))

Upvotes: 4

Paiman Rasoli
Paiman Rasoli

Reputation: 1214

You can also use array.map function with an if to check if the value not exist or empty:

arr.map((item, index) => {
 if (!item?.deptName) {
     console.log(`array index =>[${index}] is null or empty.`);
    }
 });

Upvotes: 1

Related Questions