/    Sign up×
Community /Pin to ProfileBookmark

Looping thorough an array and rename an element based on index value.

Here is my array:
var cars = [“BMW|2”, “Volvo|2″,”Saab|3”, “Ford|1”, “Fiat|1”, “Audi|1”];
I need to go through the array and split the array by “|” and rename the array element zero based on array element 1
Example: “BMW|2” i need to rename this to: BMW_1,BMW_2
“Saab|3” i need to rename this to: Saab1,Saab2,Saab3
So I am looking for guidance and `directions`

`var cars = [“BMW|2”, “Volvo|2″,”Saab|3”, “Ford|1”, “Fiat|1”, “Audi|1”];

var text = “”;
for (var i = 0; i < cars.length; i++) {
text += cars[i] + “,” ;
//gs.log(“test”);

}

gs.log(text); //BMW|2,Volvo|2,Saab|3,Ford|1,Fiat|1,Audi|1

`

to post a comment
JavaScript

3 Comments(s)

Copy linkTweet thisAlerts:
@daveyerwinJul 12.2021 — @eskinderhaile#1634070

``<i>
</i>&lt;script&gt;
"use strict"
var cars = ["BMW|2", "Volvo|2","Saab|3", "Ford|1", "Fiat|1", "Audi|1"];
var car,carss=[],cnt,num;
while(car=cars.shift()){
num=1;
cnt=car[car.length-1];
car = car.substring(0,car.length-1);
while(cnt--)carss.push(car+num++);
}
alert(carss);
&lt;/script&gt;<i>
</i>
``

if there is any part of this code you do not understand

please ask questions
Copy linkTweet thisAlerts:
@eskinderhaileauthorJul 13.2021 — Thank you DaveyErwin! This is perfect:)
Copy linkTweet thisAlerts:
@daveyerwinJul 13.2021 — @eskinderhaile#1634097 said ...

Thank you DaveyErwin! This is perfect🙂


- - - - - - - - - - - - -

No, it is not "perfect".

The code is "fragile", it will break if

the number is greater than 9
×

Success!

Help @eskinderhaile spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.20,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...