Javascript: Generic get next item in array
I think that an object could be probably a better data structure for this kind of task
items = {
ball : "1f7g",
spoon: "2c8d",
pen : "9c3c"
}
console.log(items['ball']); // 1f7g
Cycled items from array this might be useful
const currentIndex = items.indexOf(currentItem);
const nextIndex = (currentIndex + 1) % items.length;
items[nextIndex];
The first item will be taken from the beginning of the array after the last item
Try this String.prototype
function:
String.prototype.cycle = function(arr) {
const i = arr.indexOf(this.toString())
if (i === -1) return undefined
return arr[(i + 1) % arr.length];
};
Here is how you use it:
"a".cycle(["a", "b", "c"]); // "b"
"b".cycle(["a", "b", "c"]); // "c"
"c".cycle(["a", "b", "c"]); // "a"
"item1".cycle(["item1", "item2", "item3"]) // "item2"
If you want to do it the other way round, you can use this Array.prototype
function:
Array.prototype.cycle = function(str) {
const i = this.indexOf(str);
if (i === -1) return undefined;
return this[(i + 1) % this.length];
};
Here is how you use it:
["a", "b", "c"].cycle("a"); // "b"
["a", "b", "c"].cycle("b"); // "c"
["a", "b", "c"].cycle("c"); // "a"
["item1", "item2", "item3"].cycle("item1") // "item2"
You've almost got it right, but the syntax is arr[x]
, not arr(x)
:
index = array.indexOf(value);
if(index >= 0 && index < array.length - 1)
nextItem = array[index + 1]
BTW, using an object instead of an array might be a better option:
data = {"ball":"1f7g", "spoon":"2c8d", "pen":"9c3c"}
and then simply
code = data[name]