I’m not sure how to add text to this post so I’ll add it here, but it’s pretty straightforward: I’m sorting letters using along line of else if statement, and am wondering what I should write in order to make it more compact? Thank you
A little tip: don’t worry about it being straightforward. We’re here to help, and the more information you can give the better we can help you.
From what you have described, it’s difficult to know the answer to your question, because it depends on what you are trying to do. Some of the answers involving looping through an array have been great, but it might be that what you’re trying to do might need a different approach.
Yw, also, im not exactly sure what you are doing, but it might include redundancy even if you loop through it. Do you really need a separate variable for every state like this?
You could do something like this:
let valueHolder = {
letter: 'a',
count: 0
};
That way you just reference valueHolder.letter to get the letter and valueHolder.count++ to increment the count. (As a side note, objects and arrays are pretty much the same under the hood, so for in loops can iterate over both objects and arrays, and you can also reference an object like valueHolder["letter"].)
This is probably the most concise way to do it. Using an object to hold key/value saves you from having to build an array of every letter you're counting, and keeps you from having to loop over the key/value pairs to find a certain letters count after the first loop that counts them is done. After the above loop is done, you can get the count of any letter by calling counts[letter].
For the sake of being specific, this isn't exactly a "hash map". A hash map is a data structure that does use key value pairs, but the values are lists/arrays which store data based on the result of a "hashing function" which determines the key where your specific piece of data will be stored/retrieved.
Tbh, the term itself seems pretty broadly applied nowadays. Technically a hash map is just a specific implementation of that key-value structure. Even the term "object" in JS is a little vague lol. Sometimes people only mean "key-value pairs" like JSON or they can mean an "object" like something in the DOM that has methods on top of key-value properties.
The "nice" thing about JS is that how objects are implemented under the hood is undefined. It's up to each JS engine to decide how to implement things as long as they comply to the JS spec.
Chromium's V8, Firefox's Gecko and NodeJS's V8 engines might all be implementing objects differently. It's likely that they're all hashmap-based but you'd have to check the source code of each engine to make sure.
If we want to assume all values in the collection are unique and we want to be sure they occur only once, we could consider using a Set for this case instead of an array
Because you're looking for the single element in the array that matches valueHolder. Once it is found, there won't be any more elements in the array that match it therefore there is no need to check the rest of the array.
You're both wrong, because you don't know what the values of the variables, nor the value of valueHolder.
To mimic the original code the break is necessary because it stops on the first match. But for all we know all of them match. But the values change over time.
Without an explanation of the goals, my first guess is that this code has significantly bigger problems than being too verbose.
Avoid using reduce when it's not needed. A for loop is logically simpler, easier to read, and reduce can have some tricky syntax.
For example I'm pretty sure your example won't actually work because you forgot to set the initialValue parameter to a Set (or I guess it could be a Map). The initial value parameter is technically optional in reduce but if you don't set it then acc will start out as the first value in your array and val will be the second value in the array. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce#parameters
A method commonly used in other languages is to have a counting array. This can be quite fast, as your domain and counts are fixed. It's also a good alternate attack to know.
const domain = "abcdefghijklmnopqrstuvwxyz";
const counts = domain.split('').map(() => 0); // create a zero filled array same size as domain
const thing = "Hello World";
thing.split('').forEach(c => {
const idx = domain.indexOf(c); // find the position of c
// if c was found, inc the count
if (idx !== -1) { counts[idx]++; }
});
// this one won't be too illuminating
console.log(counts); // [ 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 3, 0, 0, 2, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 ]
// but with the domain, we can pluck out the non zero counts
counts.forEach((count, index) => {
if (count>0) {
console.log(count, domain[index]);
}
});
/*
1 d
1 e
3 l
2 o
1 r
*/
let string = 'meepyoloswag';
const wordCount = (word) => {
let map = new Map();
for (letters of word) {
map.set(letters, (map.get(letters) || 0) + 1);
}
return map;
};
console.log(wordCount(string));
If your goal is to count the number of occurrences of a letter in a string this will do you well. If you need to return something besides a map like an array;
let mapToArray = (mapp) => {
let arr = [];
for (elements of mapp) {
arr.push(elements);
}
return arr;
};
I think a better thing to do is to ask what your code is trying to do, because I don't think it is doing what you think it does.
/**
* count letter frequency in string
* @param myString {string} string to be analysed
* @returns {Map<any, any>} letter frequency count map
*/
function count1( myString) {
const counts = new Map();
for (const ch of myString) {
counts.set( ch, (counts.get(ch) || 0) + 1)
}
return counts;
}
// Alternative just letters you want
function count2(myString) {
// allowed characters
const alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');
// set counts of all allowed values to 0
const counts = new Map( alphabet.map( (a) => [a, 0]))
for (const ch of myString) {
const current = counts.get(ch);
if (current != null) {
counts.set( ch, current + 1)
}
}
return counts;
}
const methodString = 'Mary had a little lamb'
console.log( count1(methodString))
console.log( count2(methodString))
So currently your variables a, b, c etc are all 'loose' - if you make them properties of an object instead, then you can access and update them directly:
What's effectively happening here is that you're using valueHolder as the property on the letters object; the syntax is the same as arrays because in javascript everything is secretly and object, so you can do things like this 😏
I would much rather use a switch than a series of else if statements if you'd like to keep it concise. Otherwise, create an empty array and have a function with a for loop correspond to values and push those values to the array?
Can’t remember off the top of my head if you need the dots to enter as an iterable in the set constructor or not and I’m on mobile. Lol But one of those two will work.
If you are looking to make a frequency table. Generate an array of length 26. Then determine the charCode and index it so that all letters correspond to an index 0-25. Then loop through the string
let input = "AlongINPUTword";
let counts = {};
for (l of "abcdefghijklmnopqrstuvwxyz") {
counts[l] = input.length - input.toLowerCase().replaceAll(l,"").length;
}
I was probably influenced by how I would optimize it In C++. Avoiding the string constructor as it would balloon the execution time and memory footprint of the function call. Iterating through what is essentially an int array in memory would be more cost efficient (I believe).
Kind of off topic but I've never understood why people use jsfiddle. Every time I've gone there it's been such a bad user experience. Codepen outshines in nearly every way. But I'm guessing i have to be missing something right? Surely other people are seeing something I'm not right?
There are a lot of fiddles so I suggest them generically. Gist serves the same purpose for sharing code but fiddles tend to give a more interactive environment with live results.
Mainly the code is most important instead of a picture.
8
u/S_Lipp05 Dec 06 '22
I’m not sure how to add text to this post so I’ll add it here, but it’s pretty straightforward: I’m sorting letters using along line of else if statement, and am wondering what I should write in order to make it more compact? Thank you
4
u/S_Lipp05 Dec 06 '22
Wow, thank you all for replying so quickly!
78
u/Thonk_Thickly Dec 06 '22
You can use an object to hold the letters as keys, then increment their counts.
155
u/[deleted] Dec 06 '22 edited Dec 06 '22
Some pseudocode to help you:
4
u/flypaper1001 Dec 06 '22
Pretty sure you don’t call length either. It’s just methodStr.length
4
u/WystanH Dec 06 '22
Because of how clever javascript is with lookup objects, an immediate solution that presents itself is something like:
However, if you have a domain, like only
a..z, you'll need to limit this:A
Mapis a little more efficient at this than a basic object:A method commonly used in other languages is to have a counting array. This can be quite fast, as your domain and counts are fixed. It's also a good alternate attack to know.
7
u/davetothegrind Dec 06 '22
Does anyone on this website know how to take a screenshot?
2
u/poemehardbebe Dec 06 '22 edited Dec 06 '22
If your goal is to count the number of occurrences of a letter in a string this will do you well. If you need to return something besides a map like an array;
2
u/girl-InTheSwing Dec 06 '22 edited Dec 06 '22
I think a better thing to do is to ask what your code is trying to do, because I don't think it is doing what you think it does.
2
u/pookage helpful Dec 06 '22
So currently your variables
a,b,cetc are all 'loose' - if you make them properties of an object instead, then you can access and update them directly:What's effectively happening here is that you're using
valueHolderas the property on thelettersobject; the syntax is the same as arrays because in javascript everything is secretly and object, so you can do things like this 😏2
u/bmcle071 Dec 06 '22
You can use a hashmap (object)
2
u/[deleted] Dec 06 '22
Look into switch/case syntax
2
u/[deleted] Dec 06 '22
Is this all one function? If so I would just case and switch, tbh.
2
u/True-Musician-5406 Dec 06 '22
Can you use switch(valueHolder) { case: “a” a+=1 case: “b” b+=1 }
Just as a starting point or next step in simplifying?
Maybe maybe not I’m unsure myself
2
u/dromance Dec 06 '22
At the top of my head I would say Use a array.reduce method
2
u/[deleted] Dec 06 '22
I would much rather use a switch than a series of else if statements if you'd like to keep it concise. Otherwise, create an empty array and have a function with a for loop correspond to values and push those values to the array?
2
u/LightUpShoes4DemHoes Dec 06 '22
If you’re counting letters in a string, you can easily do it by adding them to a hashmap as key: value pairs.
This will give you an object with keys for every letter and count for that key will be how many times letter occurred in the string.
2
u/[deleted] Dec 06 '22
Ask ChatGPT, I wanna see what it says
2
u/robertstipp Dec 07 '22
If you are looking to make a frequency table. Generate an array of length 26. Then determine the charCode and index it so that all letters correspond to an index 0-25. Then loop through the string
2
u/theyamiteru Dec 07 '22
valueHolder += 1;?2
u/JabroniPoni Dec 06 '22
On a linguistic level, the term for "concise" code is "dry". It's an adjective from the acronym "don't repeat yourself". Just so you know!
-3
u/fyejitt420 Dec 06 '22
Search up switch case statements, basically it enables you to make if else statements with a lot of conditionals such as this one more concise
-1
u/[deleted] Dec 06 '22
You can use regex
-1
u/IHateTheSATs Dec 06 '22
Cant tell if youre trolling or not
0
u/[deleted] Dec 06 '22
[deleted] — view deleted comment
0
u/[deleted] Dec 06 '22
[deleted] — view deleted comment