Answer to Question #303256 in HTML/JavaScript Web Application for king

Question #303256

Replacing array Item

Given an array myArray, targetItem and a replace item write a JS program to replace the targetItem with the given replacement in myArray consists of more than one targetItem replace the first occurence.


sample input1

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

'four'

4

sample output1

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


function readLine() {

 return inputString[currentLine++];

}


function main() {

 let myArray = JSON.parse(readLine().replace(/'/g, '"'));

 let targetItem = JSON.parse(readLine().replace(/'/g, '"'));

 let replaceItem = JSON.parse(readLine().replace(/'/g, '"'));


 /* Please do not modify anything above this line */


 /* Write your code here and log the output */

}



1
Expert's answer
2022-03-02T03:04:47-0500
function readLine() {
    return inputString[currentLine++];
}
   
function main() {
    let myArray = JSON.parse(readLine().replace(/'/g, '"'));
    let targetItem = JSON.parse(readLine().replace(/'/g, '"'));
    let replaceItem = JSON.parse(readLine().replace(/'/g, '"'));

    /* Please do not modify anything above this line */

    /* Write your code here and log the output */
    
    for (let i = 0; i < myArray.length; i++) {
        if (myArray[i] == targetItem) {
            myArray[i] = replaceItem;
            break
        }
    }

    console.log(myArray)
}

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