Skip to content
Advertisement

How to replace item in array?

Each item of this array is some number:

JavaScript

How to replace some item with a new one?

For example, we want to replace 3452 with 1010, how would we do this?

Advertisement

Answer

JavaScript

Also it is recommend you not use the constructor method to initialize your arrays. Instead, use the literal syntax:

JavaScript

You can also use the ~ operator if you are into terse JavaScript and want to shorten the -1 comparison:

JavaScript

Sometimes I even like to write a contains function to abstract this check and make it easier to understand what’s going on. What’s awesome is this works on arrays and strings both:

JavaScript

Starting with ES6/ES2015 for strings, and proposed for ES2016 for arrays, you can more easily determine if a source contains another value:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement