I need to write a JS function that creates an object from a given string. String characters are object keys. Repeated characters should not be included twice. 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 chars duplication using alreadyInArr
. However when I log my alreadyInArr
, it's 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 output is:
charsArr is: [ 'a', 'a', 'a', 'b', 'c' ]
alreadyInArr is: []
{ a: 0, b: 0, c: 0 }
Can someone explain, why alreadyInArr
is empty and yet function still works as expected?
Here's a pen: https://codepen.io/t411tocreate/pen/bYReRj?editors=0012
Your else
clause isn't reachable at all since you didn't pushed the element in the right place, you could add a console.log()
inside the loop to see that the array still empty through all the iterations.
Instead, the element should be pushed in the if condition like :
for (var i = 0; i < charsArr.length; i++) {
if (!alreadyInArr.includes(charsArr[i])) {
charsObj[charsArr[i]] = 0;
alreadyInArr.push(charsArr[i]);
}
}
Hope this helps.
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;
alreadyInArr.push(charsArr[i]);
}
}
console.log("alreadyInArr is:", alreadyInArr);
return charsObj;
}
console.log(objFromStr("aaabc"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With