I need to write a JS function that creates an object from a given string. String characters are object characters. Repeated characters should not be included twice. The values of all keys are zero.
Example: input objFromStr("aaabc")
should return{a: 0, b: 0, c: 0}
Here is my solution:
function objFromStr(inStr) {
let charsArr = inStr.split("");
let charsObj = {};
var alreadyInArr = [];
for (var i = 0; i < charsArr.length; i++) {
if (!(alreadyInArr.includes(charsArr[i]))) {
charsObj[charsArr[i]] = 0;
} else {
alreadyInArr.push(charsArr[i]);
}
}
return charsObj;
}
This solution works as expected, but I don't understand why. I check for duplicate characters with alreadyInArr
. However, when I record my own alreadyInArr
, it is empty.
So, after running this code:
function objFromStr(inStr) {
let charsArr = inStr.split("");
console.log("charsArr is:", charsArr);
let charsObj = {};
var alreadyInArr = [];
for (var i = 0; i < charsArr.length; i++) {
if (!(alreadyInArr.includes(charsArr[i]))) {
charsObj[charsArr[i]] = 0;
} else {
alreadyInArr.push(charsArr[i]);
}
}
console.log("alreadyInArr is:", alreadyInArr);
return charsObj;
}
console.log(objFromStr("aaabc"));
My conclusion:
charsArr is: [ 'a', 'a', 'a', 'b', 'c' ]
alreadyInArr is: []
{ a: 0, b: 0, c: 0 }
Can someone explain why it is alreadyInArr
empty, and yet the function still works as expected?
Here's the handle: https://codepen.io/t411tocreate/pen/bYReRj?editors=0012
source
share