Skip to content Skip to sidebar Skip to footer

How To Search For The Value With A Certain Index In An Array And Modify Its Value?

I have two arrays, the first contains two numbers and the second 12 values. firstArray = [0, 6]; secondArray = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'Au

Solution 1:

For a oneliner, you could use map from Array.prototype:

secondArray = secondArray.map((element, index) => firstArray.includes(index) ? "blank" : element )

Please note the map function returns a new array, instead of modifying the original one.

Edit: removed redundant return and curly-braces around the arrow function body

Solution 2:

firstArray = [0, 6]; 
secondArray = ["January", "February", "March", "April", "May", "June", "July","August", "September", "October", "November", "December"];

for(let i = 0; i < firstArray.length; i++) {
    secondArray[firstArray[i]]="blank";
}
console.log(secondArray);

PS: All you need to do just loop through the first array, and the update the values of second array at index

Solution 3:

firstArray.map(e=>{if(secondArray[e]){secondArray[e]="blank"}})

Post a Comment for "How To Search For The Value With A Certain Index In An Array And Modify Its Value?"