PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, October 28, 2022

[FIXED] How to get index of an empty element of an array?

 October 28, 2022     arrays, element, is-empty, isnullorempty, javascript     No comments   

Issue

I have a JavaScript array with some empty (maybe null or undefined) elements. I need to find those empty indexes (1 and 3).

['red',,'orange',,'blue','white','black']

But my solution is not working:

for (let i = 0; i < array.length; i++) {
    if (array[i] === undefined) { // Same problem with null or ''
        console.log('No color: ' + i);
    }
}

Snippet:

const array = ['red', , 'orange', , 'blue', 'white', 'black'];

for (let i = 0; i < array.length; i++) {
  if (array[i] === undefined) { // Same problem with null or ''
    console.log('No color: ' + i);
  }
}


Solution

Use a blank string to compare to get the answer you desire. If you also want to check for undefined you can use logical or to check both of them.

const array = ['red','',  'orange',,  'blue', 'white', 'black'];

for (let i = 0; i < array.length; i++) {
  if (array[i] === '' || array[i] === undefined) { 
console.log('No color: ' + i);
}
}


Answered By - varisha15
Answer Checked By - Willingham (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing