Modifying array in JavaScript | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Modifying array in JavaScript

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 for this

24th Apr 2022, 3:49 AM
Dec Fathani
Dec Fathani - avatar
5 Answers
+ 2
Or use array method, map const fruits2 = fruits.map(fruit => fruit ? fruit : "new fruit");
30th Apr 2022, 1:44 AM
Calviղ
Calviղ - avatar
+ 1
Calviղ thanks for adding
10th May 2022, 12:48 PM
Dec Fathani
Dec Fathani - avatar
0
reduce() reduce() loops through original array, and then returns a "result" (Not necessarily an array). reduce() accepts two parameters: 1. A reducer function 2. Initial Value For the reducer function, it accepts two to four parameter: 1. Accumulator 2. Each item of original array 3. (Optional) Index of the item in original array 4. (Optional) Original Array Demo: https://code.sololearn.com/cqHxL5WFU1PQ/?ref=app Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
24th Apr 2022, 4:01 AM
Gordon
Gordon - avatar
0
i still don't now how to do this with reduce(), i just found that it can be done using forEach, thanks to those who helped me out this https://code.sololearn.com/Wreb0vw95HVN/?ref=app
24th Apr 2022, 5:33 AM
Dec Fathani
Dec Fathani - avatar
0
Gordon anyway thanks
24th Apr 2022, 2:05 PM
Dec Fathani
Dec Fathani - avatar