Conditionally replace values in an array in JavaScript
This post will discuss how to conditionally replace values in an array in JavaScript.
There are several ways to conditionally replace values in an array in JavaScript, depending on the criteria and the desired output. Here are some of the possible functions:
1. Using Array.map() function
The Array.map() function creates a new array with the results of calling a function on every element in the original array. We can use this function to replace values in an array based on a condition. For example, if we have an array of numbers and we want to replace all the negative numbers with zero, we can do this:
|
1 2 3 4 5 |
let arr = [1, -2, 3, -4, 5]; let newArr = arr.map(x => x < 0 ? 0 : x); console.log(newArr); // [1, 0, 3, 0, 5] |
2. Using Array.forEach() function
The Array.forEach() function executes a function for each element in an array. We can use this function to modify the original array by accessing and replacing its elements by their index. For example, if we have an array of strings and we want to replace all the empty strings with "NA", we can do this:
|
1 2 3 4 5 6 7 8 9 |
let arr = ["Anne", "", "Oliver", "", "Christopher"]; arr.forEach((x, i) => { if (x === "") { arr[i] = "NA"; } }); console.log(arr); // [ 'Anne', 'NA', 'Oliver', 'NA', 'Christopher' ] |
3. Using a loop
We can also use a loop to iterate over the array and use a conditional statement to check and replace the values based on a condition. For example, if we have an array of objects and we want to replace all the objects that have a null value for a property with a default object, we can do this:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
let arr = [ {name: "Anne", age: 25}, {name: null, age: null}, {name: "Oliver", age: 30}, {name: null, age: null}, {name: "Christopher", age: 45} ]; let defaultObj = {name: "Unknown", age: 0}; for (let i = 0; i < arr.length; i++) { if (arr[i].name === null || arr[i].age === null) { arr[i] = defaultObj; } } console.log(arr); |
Output:
[
{ name: 'Anne', age: 25 },
{ name: 'Unknown', age: 0 },
{ name: 'Oliver', age: 30 },
{ name: 'Unknown', age: 0 },
{ name: 'Christopher', age: 45 }
]
That’s all about conditionally replacing values in an array in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)