Reputation: 226
I just came across one thing and I cannot find an answer why is this happening so maybe someone can help.
This is the piece of code
function titleCase(str) {
let arr = str.split(" ")
.map(s => s.charAt(0).toUpperCase() + s.substring(1).toLowerCase())
console.log('arr1', arr)
let arr2 = str.split(" ")
arr2.map(s => s.charAt(0).toUpperCase() + s.substring(1).toLowerCase())
console.log('arr2', arr2)
}
titleCase("I'm a little tea pot");
I am interested in why arr1 (when map is chained immediately after split is working as expected. It returns ["I'm", "A", "Little", "Tea", "Pot"]
, but arr2 is returning ["I'm", "a", "little", "tea", "pot"]
Should this type of writing (whether it is chained or not) return the same key? What am I missing?
Upvotes: 1
Views: 770
Reputation: 4519
it is because in this line
let arr2 = str.split(" ")<----- this is what you get from console.log()
arr2.map(s => s.charAt(0).toUpperCase() + s.substring(1).toLowerCase())
console.log('arr2', arr2)
}
you are using console.log(arr2)
which is assinged to be equal to str.split(" ")
for you second line to work you have to assign arr2.map a variable and then you will be able to print it in the console like this
const arr2=arr2.map(s => s.charAt(0).toUpperCase() + s.substring(1).toLowerCase())
console.log('arr2', arr2)
}
Upvotes: 0
Reputation: 4057
Check out the documentation for map: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
The map() method creates a new array populated with the results
That means it doesn't change the original array, but gives you a new one. So when you do
arr2.map(s => s.charAt(0).toUpperCase() + s.substring(1).toLowerCase())
console.log('arr2', arr2)
Map is returning a new array, but you have no variable to store the new array that .map creates. So
const result = arr2.map(s => s.charAt(0).toUpperCase() + s.substring(1).toLowerCase())
console.log('result', result)
Will work.
In contrast if we check out the documentation for sort: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
The sort() method sorts the elements of an array in place
So it is changing the same array and not giving you new one.
Upvotes: 0
Reputation: 932
In the former, your variable is being assigning the result of operations split
followed by map
on your array. In the latter, your variable is being assigned only the result of split
.
So, this:
let arr = str.split(" ")
.map(s => s.charAt(0).toUpperCase() + s.substring(1).toLowerCase())
is equivalent to:
let arr2 = str.split(" ")
arr2 = arr2.map(s => s.charAt(0).toUpperCase() + s.substring(1).toLowerCase())
i.e. you forgot to do the assignment arr2 =
in case of map
Upvotes: 1