How can I return only the first 3 characters/digits from each item in an array?
For example: The string 123456
should return 123
, 987654
should return 987
, and so on.
Given an array of:
['7177576', '4672769', '2445142', '9293878', '5764392']
Expected return:
['717', '467','244', '929', '576']
I have tried .slice()
but that returns the first three like this:
['7177576', '4672769', '2445142'].
CodePudding user response:
slice
works for strings, too.
const
data = ['7177576', '4672769', '2445142', '9293878', '5764392'],
result = data.map(string => string.slice(0, 3));
console.log(result);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
JavaScript has many methods for manipulating arrays. The map method creates a new array populated with the results of calling a provided function on every element in the calling array. As Nina Scholz mentions above you can use slice on strings as well.
The issue you are having is that you are calling slice on the array and not on the items of the array.
You need to do something like Nina Suggest which is to map over the main array and call your slice function for each item.