Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

44
Views
Is it possible to give each letter stored in an array an id?

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);
7 months ago · Juan Pablo Isaza
1 answers
Answer question

0

Short answer, for a flat array is No, it's not possible. But there are several other options.

Option #1 - Use a Map

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());

Option #2 - Use an Array of Objects

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);

Option #3 - Use a 2D Array

const words = [
  [1, "triouno stock down"],
  [2, "the great depression"],
  [3, "stock market crash"],
];
7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.