0

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.

3
  • Is this a sort of problem taken from a course of javascript? Take a look to Array.findIndex() Commented May 30, 2019 at 0:21
  • No it is not. I want to push some data in firebase with specific indexes, (1 , 2 , 3 ,4 so on ) and If I delete an element it becomes null, and I want to put the new data inside there instead of putting it at the end of the array with some wierd id that firebase generates. Commented May 30, 2019 at 0:23
  • The real question is why would you eat the cherries when you have the option of delicious strawberries or the full tasty meal of a giant Honeycrisp apple? Commented May 30, 2019 at 22:35

3 Answers 3

1

From W3C documentation :

arr.findIndex(element => element === null);

Replace :

arr[arr.findIndex(element => element === null)] = "potatoes";
Sign up to request clarification or add additional context in comments.

1 Comment

This is actually what I was looking for :D Thanks
1

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])

Comments

1

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');

1 Comment

Yes, however I don't know the index of the null element so I cant splice on it :/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.