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 */
}
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)
}
Comments
Leave a comment