0

I have an array of strings. I want to remove first character from each element of that array.

I looped through the array and tried to remove the first character by using substr method.

 var x = ["X2019","X2020","X2021","X2022"];
    
for(i = 0; i < x.length; i++) {
  result = x[i].substr(1);
}
console.log(result);

I need an array like

result = ["2019","2021","2022"];

1
  • 3
    In your example, result is not an array. Second, substr returns a new string. Third try functional looping methods like Array.map Commented Aug 21, 2019 at 7:37

2 Answers 2

12

You can use .map() and .slice() methods to get the desired output:

var x = ["X2019","X2020","X2021","X2022"];

var y = x.map(s => s.slice(1));

console.log(y);

Sign up to request clarification or add additional context in comments.

Comments

0

You are not storing value returned from substr() call in a loop. Assigning to a variable means only the last value will be available.

Declare a result array and push to it.

var x = ["X2019", "X2020", "X2021", "X2022"];
var result = []
for (i = 0; i < x.length; i++) {
    result.push(x[i].substr(1));
}
console.log(result);

Even the shorter syntax by using map() function:

var x = ["X2019", "X2020", "X2021", "X2022"];
var result = x.map(value => value.substr(1));
console.log(result);

1 Comment

Please note that answering a question this obvious is bad practice. Since you know the solution, you are more likely to form better query for such issues. You should search and vote to close such question as there are other ways and discussions that will help everyone

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.