How To Read First Character Of String Inside An Array Without Using String.charAt()?
Suppose I have an array with strings: ['1234', '1223', '5454', 'abc', 'abdd'] And I want to read the first character of each string and put it into an new array: ['1', '1', '5', '
Solution 1:
You need to use map
instead of filter
.
var strings = ["1234", "1223", "5454", "abc", "abdd"]
var firstChars = strings.map(function (string) {
return string[0];
})
console.log(firstChars)
Solution 2:
With ES6, you could use a destructuring assignment, because strings are iterables.
var array = ["1234", "1223", "5454", "abc", "abdd"];
result = array.map(([a]) => a);
console.log(result);
Solution 3:
You can use.
var testArr = ["1234", "1223", "5454", "abc", "abdd"],
newArr = [];
testArr.forEach( function(str){
newArr.push(str.substring(0,1));
});
Better functional and efficient version.
var testArr = ["1234", "1223", "5454", "abc", "abdd"];
function getFirst(arr){
return arr.map(function(str){
return str.substring(0,1);
});
}
console.log(getFirst(testArr));
Best videos for understanding the array methods The Array ForEach Method
Post a Comment for "How To Read First Character Of String Inside An Array Without Using String.charAt()?"