I have a .txt file with all the scrabble letter quantities in:
A-9, B-2, C-2, D-4, E-12, F-2, G-3, H-2, I-9, J-1, K-1, L-4, M-2, N-6, O-8, P-2, Q-1, R-6, S-4, T-6, U-4, V-2, W-2, X-1, Y-2, Z-1
I am trying to get an array of objects from this, where the key is the letter, and the value is the number.
The problem I am having is where I am trying to set the key to be the first item in the array (that I split earlier) [A, 9]
.
The code I have is as follows. Any tips would be gratefully received :)
import fs from 'fs'
var output = fs.readFileSync('scrabble-quantities.txt', 'utf-8')
.trim()
.split(', ')
.map(item => item.split('-'))
.reduce((quantities, item) => {
quantities.push({
item[0]: item[1]
})
return quantities
}, [])
Thanks
I have a .txt file with all the scrabble letter quantities in:
A-9, B-2, C-2, D-4, E-12, F-2, G-3, H-2, I-9, J-1, K-1, L-4, M-2, N-6, O-8, P-2, Q-1, R-6, S-4, T-6, U-4, V-2, W-2, X-1, Y-2, Z-1
I am trying to get an array of objects from this, where the key is the letter, and the value is the number.
The problem I am having is where I am trying to set the key to be the first item in the array (that I split earlier) [A, 9]
.
The code I have is as follows. Any tips would be gratefully received :)
import fs from 'fs'
var output = fs.readFileSync('scrabble-quantities.txt', 'utf-8')
.trim()
.split(', ')
.map(item => item.split('-'))
.reduce((quantities, item) => {
quantities.push({
item[0]: item[1]
})
return quantities
}, [])
Thanks
I would use an object instead of an array. It's easier and more natural how JS works:
// ...
.reduce((quantities, item) => {
quantities[item[0]] = item[1];
return quantities;
}, {});
The resulting output
object is then (in JSON notation):
{
"A": 9,
"B": 2,
// ...
"Z": 1
}
EDIT: mind the value type
If you want the value to be an actual number you will have to parse it in the assignment with:
parseInt(item[1], 10)
To create a key (property name) dynamically, you need to do one of two things:
In ES5 and earlier, you have to create the object and then set the property:
var o = {};
o[item[0]] = item[1];
In ES2015 (aka ES6) and later, you can use a dynamic property name in a property initializer via []
:
// ES2015 (ES6) ONLY
quantities.push({
[item[0]]: item[1]
})
That said, I'd e at the problem differently, using regex and ending up with an object keyed by the letter rather than an array of objects:
var str = "A-9, B-2, C-2, D-4, E-12, F-2, G-3, H-2, I-9, J-1, K-1, L-4, M-2, N-6, O-8, P-2, Q-1, R-6, S-4, T-6, U-4, V-2, W-2, X-1, Y-2, Z-1";
var quantities = {};
str.match(/[A-Z]-\d/g).forEach(function(entry) {
quantities[entry.charAt(0)] = +entry.replace(/.-/, '');
});
console.log(quantities);
Then, looking up the quantity of a letter bees quantities.A
(or quantities[letter]
if letter
is a variable containing "A"
):
console.log(quantities.A); // 9