New course! Every coder should learn Generative AI!
Try a free lesson0
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
5 Answers
+ 2
Or use array method, map
const fruits2 = fruits.map(fruit => fruit ? fruit : "new fruit");
+ 1
Calviղ thanks for adding
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
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
0
Gordon anyway thanks