How to Increment the Elements of an Array by a Desired Value in JavaScript

increment a value in an array if a match is found

You can use Array.find to find the item in the array whose value property is 'movie#3', then increment it's voteCount property.

const movies=[{label:"movie#1",value:"movie#1",voteCount:0},{label:"movie#2",value:"movie#2",voteCount:0},{label:"movie#3",value:"movie#3",voteCount:0},{label:"movie#4",value:"movie#4",voteCount:0}];

const choice = 'movie#3'

function vote(movieList, vote){
movieList.find(e => e.value == vote).voteCount++;
}

vote(movies, choice)

console.log(movies)

Javascript 2-dimensional array: incrementing a specific item's value

Objects (Arrays are Objects too) are passed as references. That means that your array looks like this (pseudostructure):

 arr2 -> [1, 2, 3]
arr1 -> [ -> arr2, -> arr2 -> arr2]

Therefore arr1[0] is just the same as arr1[1] or arr2. To create three different arrays copy the array:

 arr1.push([...arr2]);

Increment array values?

Just add the previous value, or 0 if no such value exists

var arr  = [2,2,2,2,2];var arr2 = []; // <----- new array
for (var i=0; i<arr.length; i++) { arr2[i] = arr[i] + (arr2[i-1] || 0)}
document.body.innerHTML = '<pre>' + JSON.stringify(arr2, null, 4) + '</pre>';

With JavaScript how would I increment strings using an array to create a loop?

You need to save a counter to localStorage that you can retrieve on each page load, increment,, make the check, and then save again.

$(function () {

const images = [
'wallpaper1',
'wallpaper2',
'wallpaper3',
'wallpaper4'
];

// We must check to see if localStorate exists before
// we do anything
function hasLocalStorage() {
try {
localStorage.setItem('count', 0);
if (localStorage.getItem('count') === '0') {
return true;
}
} catch(e) {
return false;
}
return false;
}

// Fetch the count from localStorage. Because it's
// saved as a string we need to coerce it to a number
let count = Number(localStorage.getItem('count'));

$("#hero").css({
'background-image': `url(${images[count]})`
});

// Increase the count
count++;

// If the count is the length of the array (minus one
// because the array is indexed-based) set the
// localStorate count to zero, otherwise save the count
if (count === images.length - 1) {
localStorage.setItem('count', 0);
} else {
localStorage.setItem('count', count);
}

});


Related Topics



Leave a reply



Submit