0

let fruits = ['apple' , 'cherry', 'grape', undefined, 'lemon' ,'melon'];

i have those array of fruits. i want to replace undefined with another fruit, and return all the array with new fruit included. how to do that using array method in javascript i do need help

asked Apr 24, 2022 at 4:53

4 Answers 4

1

You use .splice to replace undefined with new fruit. But just note that it's also possible to achieve it with .map and .filter

let arr = ['apple' , 'cherry', 'grape', undefined, 'lemon' ,'melon'];
 
let index = arr.indexOf(undefined)
arr.splice(index, 1, 'new fruit')
console.log(arr)

answered Apr 24, 2022 at 5:01
Sign up to request clarification or add additional context in comments.

Comments

1

You can use Javascript splice method

let fruits = ['apple' , 'cherry', 'grape', undefined, 'lemon' ,'melon'];
fruits.splice(fruits.indexOf(undefined),1,"newFruit")
console.log(fruits)

answered Apr 24, 2022 at 5:03

Comments

1

This is a basic example of what loops are used for. You can use for, or forEach.

let fruits = ['apple' , 'cherry', 'grape', undefined, 'lemon' ,'melon'];
fruits.forEach((fruit,index) => {
 if(fruit == undefined) {
 fruits[index] = 'Some other fruit'
 }
})
console.log(fruits)

answered Apr 24, 2022 at 5:09

1 Comment

thanks, now i know how to use index parameter for looping in forEach
1

One of ways we can do this is also by using maps as norbekoff told. But the result should be stored in a new Array.If you want to do it inplace then you can go with splice method.

let arr = ['apple' , 'cherry', 'grape', undefined, 'lemon' ,'melon'];
 
let newArr=arr.map((ele)=>{
 if(!ele){
 ele="new Fruit";
 }
 return ele;
 });
 
console.log(newArr);

answered Apr 24, 2022 at 5:38

1 Comment

thanks, another way to find the undefined

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.