In JavaScript, developers need that they need to update the value of an array element. It is just as easy as assigning a new value to a variable using an assignment operator. So in this article, we will see it
Update array value with static index
let colours = ["Red", "Orange", "Yellow", "Olive", "Green"];
console.log(colours);
// Output -> ["Red", "Orange", "Yellow", "Olive", "Green"]
colours[2] = "Blue";
console.log(colours);
// Output -> ["Red", "Orange", "Blue", "Olive", "Green"]
Console screenshot for update array element
Update Array Element
Update array value by searching value
let colours = ["Red", "Orange", "Yellow", "Olive", "Green"];
console.log(colours);
// Output -> ["Red", "Orange", "Yellow", "Olive", "Green"]
let index = colours.indexOf("Yellow");
colours[index] = "Blue";
console.log(colours);
// Output -> ["Red", "Orange", "Blue", "Olive", "Green"]
// One-liner
colours[colours.indexOf("Green")] = "Aqua";
console.log(colours);
// Output -> ["Red", "Orange", "Blue", "Olive", "Aqua"]
Console screenshot for an element searching by value with indexOf method
Update Array Element Searching By Value With IndexOf Method
Hope you like this!
Keep helping and happy ๐ coding
Related Articles
Deepen your understanding with these curated continuations.
Convert array to an object in JavaScript
This article explains simplest and quickest way to convert array to an object in JavaScript. Using widely accepted spread operator `...` makes easy to do it.
Flatten an Array One Level Deep in Javascript
This article explains to flatten an array one level deep in javascript comparing with lodash _.flatten method.
Identify whether device is a mobile or desktop
This article explains to flatten an array one level deep in javascript comparing with lodash _.flatten method.