RMMZ [Javascript] Shifting only select elements of array?

ct_bolt

Creator
Veteran
Joined
May 3, 2012
Messages
954
Reaction score
520
First Language
Javascript
Primarily Uses
RMMZ
Another one for ya guys... kind of has me stumped...

Shifting only select elements of array while keeping the rest of the array as is though.

Example:
Code:
const a = ["A", 4, "B", "C", "D", 1, 2, 3];
How would I shift only the numbers while keeping the rest of the array as is.

So the first shift should end up like this:
Code:
["A", 3, "B", "C", "D", 4, 1, 2]
Second shift like this:
Code:
["A", 2, "B", "C", "D", 3, 4, 1]
Thanks again for any/all help advice. :cutesmile:
 

Nolonar

Veteran
Veteran
Joined
Feb 18, 2018
Messages
161
Reaction score
242
First Language
French, German
Primarily Uses
RMMZ
You can do this:
Code:
a = a.map(element => typeof element === "number" ? shift(element) : element);
This will give you a new array where only numbers have been shifted.
As for the shift method, you probably want this:
Code:
const shift = n => n - 1 || 4;
Obviously, n has to be greater than 0, otherwise you'll get negative numbers.

For more control you can also define shift this way:
Code:
const shift = (n, max) => n - 1 || max;
 

 Masked 

Assistant
Veteran
Joined
Oct 28, 2015
Messages
90
Reaction score
261
First Language
Portuguese
Primarily Uses
RMMZ
I think you'll need to give a bit more detail on the logic of what you're trying to achieve with this one, from what you've said the only thing it can think of is swapping the elements on the array, like this:

JavaScript:
const a = [1, "a", 3, "b", "c", 4];

let aux = a[2];
a[2] = a[5];
a[5] = aux;
Aside from that, is there any particular reason to have strings and numbers mixed on the same array? It's usually not very good to have elements that behave differently on a collection. If you can split this into two arrays, one for strings and another for integers, then it's a lot easier to do (just pop and unshift).
 

Users Who Are Viewing This Thread (Users: 0, Guests: 1)

Latest Threads

Latest Posts

Latest Profile Posts



Slaving away at more maps. :LZSwink:
Accidentally zoomed the browser in on the forums page, here... and I think I'm going to just leave it. #OldPeopleProblems
Spooktober Spooktacular Game Jam Winners announcements start now! Live on stream! See who won!
so, I've begun the process of restructuring my game's base setup entirely after feeling disheartened with progress and talking to a friend. I think I'm headed in the right direction now.
Tomorrow is Thanksgiving, and I'm so excited! I've been exploring MZ a little, and I just downloaded Effekseer to make new animations. I have experience in 3D animation software, so I'll be pretty good at the whole "particle" thing. My first game on MZ will be Fantasy Force--starring a griffin, a dragon, and a pegasus fighting against the Dragon of Darkness.

Forum statistics

Threads
105,521
Messages
1,014,366
Members
137,202
Latest member
zbzikowany
Top