I am trying to give each letter in an array an Id, currently I have found a way to give each item in an array a Id, but I want to do it for each letter. Is this possible for the current format I have?
const words = [
"triouno stock down", //Sunday
"the great depression", //Monday
"stock market crash", //Tuesday
"ancient egyptian pyramids", //Wednessday
"nine one one", //Thrusday
"i am stupid", //Friday
"share my game", //Saturday
];
words.forEach((item, i) => {
item.id = i + 1;
});
console.log(words);
Short answer, for a flat array is No, it's not possible. But there are several other options.
A Map
object holds key-value pairs. So you could associate ID with value. In your example:
const words = new Map([
[1, 'triouno stock down'],
[2, 'the great depression'],
[3, 'stock market crash'],
[4, 'ancient egyptian pyramids'],
]);
// Get single value by ID
console.log(words.get(1));
// Get all values
console.log(...words.values());
const words = [
{ id: 1, message: 'triouno stock down' },
{ id: 2, message: 'the great depression' },
{ id: 3, message: 'stock market crash' },
];
// Print all words
words.forEach((word) => {
console.log(word.message);
});
// Get a specific word (this case, id = 1)
console.log(words.find((word) => word.id === 1).message);
const words = [
[1, "triouno stock down"],
[2, "the great depression"],
[3, "stock market crash"],
];