Answer to Question #205995 in HTML/JavaScript Web Application for Praveen

Question #205995

Replacing Array Item

Given an array

myArray, targetItem, and a replaceItem, write a JS program to replace the targetItem with the given replaceItem in myArray. If myArray consists of more than one targetItem replace the first occurrence.Input

  • The first line of input contains an array myArray
  • The second line of input contains a targetItem
  • The third line of input contains a replaceItem

Output

  • The output should be an array containing the replaced item.

Sample Input 1

[1, 2, 3, "four", 5, 6]

"four"

4

Sample Output 1

[ 1, 2, 3, 4, 5, 6 ]

Sample Input 2

[22, 44, 88, 352, 352]

352

176

Sample Output 2

[ 22, 44, 88, 176, 352 ]




1
Expert's answer
2021-06-11T17:02:27-0400
function replace(myArray, targetItem, replaceItem) {
    for (let i = 0; i < myArray.length; i++) {
        if (myArray[i] === targetItem) {
            myArray[i] = replaceItem;
            break;
        }
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS