Reputation: 501
So I have an array let's say :
var arr = ['apples' , 'cherries' , 'strawberries']
and after so much coding, I get hungry so I eat the 'cherries'
so now I have
arr = ['apples',null,'strawberries']
So I was wondering if there is some sort of JavaScript function that can return the first null element inside an array ?
Let's say for instance my grandma gives me 'potatoes'
and I want to add them inside the null space I have like a good boy I am, and I need the index of that null element so I may know where to place my sweet goods from grandma.
Upvotes: 0
Views: 660
Reputation: 11
try removing the element using below code :
var arr = ['apples' , 'cherries' , 'strawberries'];
arr.splice(1,1);
and remove and add try :
var arr = ['apples' , 'cherries' , 'strawberries'];
arr.splice(1,1, 'potatoes');
Upvotes: 1
Reputation: 18515
Since null
is a falsy value you can simply use Array.findIndex and match on falsy values:
var arr = ['apples',null,'strawberries']
let index = arr.findIndex(x => !x)
console.log(index)
console.log(arr[index])
Upvotes: 1
Reputation: 717
From W3C documentation :
arr.findIndex(element => element === null);
Replace :
arr[arr.findIndex(element => element === null)] = "potatoes";
Upvotes: 1