JavaScript program to split an array of strings into sets of arrays based on alphabetical order

I am looking to split an array of strings into multiple arrays based on alphabetical order. Can you help me achieve this?

For example:

let array = ['cheese', 'corn', 'apple', 'acorn', 'beet', 'banana', 'yam', 'yucca']

// the desired outcome is:

a = ['apple', 'acorn']
b = ['banana', 'beet']
c = ['cheese', 'corn']
y = ['yam', 'yucca']

Answer №1

When you have an array of words like

let words = ["corn", "to", "add", "adhere", "tree"]

You can organize them into sections using this function:

const getSections = () => {
    if (words.length === 0) {
        return [];
    }
    return Object.values(
        words.reduce((acc, word) => {
            let firstLetter = word[0].toLocaleUpperCase();
            if (!acc[firstLetter]) {
                acc[firstLetter] = { title: firstLetter, data: [word] };
            } else {
                acc[firstLetter].data.push(word);
            }
            return acc;
        }, {})
    );
}

This will group the words nicely, such as

[{title: 'T', data: ["to", "tree"]}, ...]

which is great for use with the SectionList component in ReactNative.

Answer №2

Instead of assigning values to individual variables, a more efficient approach would be to create a dictionary object. This can be easily achieved using the reduce() method:

let fruits = ['apple', 'banana', 'cherry', 'date', 'fig', 'grape', 'kiwi', 'lemon']

let dictionary = fruits.reduce((acc, fruit) => {
    // Use the first letter as the key for the dictionary entry
    let key = fruit[0].toLocaleUpperCase()

    // Check if key already exists, then add to it; otherwise, create a new entry
    if (acc[key]) acc[key].push(fruit)
    else acc[key] = [fruit]

    return acc
}, {})

console.log(dictionary)

// Retrieve all the fruits starting with 'A'
console.log(dictionary['A'])

It is important to ensure that the original array contains meaningful data for this to work effectively.

Answer №3

If you have an array, you can create a Map object and populate it using the first character of each string in the array as the key:

let array = ['cheese', 'corn', 'apple', 'acorn', 'beet', 'banana', 'yam', 'yucca'];

let map = ((m, a) => (a.forEach(s => {
  let a = m.get(s[0]) || [];
  m.set(s[0], (a.push(s), a));
}), m))(new Map(), array);

console.log(map.get("a"));
console.log(map.get("b"));
console.log(map.get("c"));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the mechanism behind the setTimeout function as an asynchronous timer when we specify a specific duration?

Can you identify the coding instructor, possibly Net Ninja or Fireship, who explained that in asynchronous setTimeout, it promises to run after a minimum time of 1 second but may actually take longer (e.g. 1015 milliseconds or 1200 milliseconds)? What ha ...

When trying to publish a new post using postman, the content including the title, message, and image is not displaying

I am currently learning how to build a REST API by following a tutorial. Below is an excerpt from my server.js file: import express from 'express'; import compression from 'compression'; import bodyParser from 'body-parser'; ...

Click the mouse to create a unique path from the list items within the <ul> <li> using jQuery

My current listing contains various files and folders: <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fon ...

Transmit information using express handlebars in a straightforward node application

Struggling to pass data from express handlebars to index.html? Check out my code below: server.js code: const express = require('express'); const app = express(); const expressHandlebars = require('express-handlebars'); const path = r ...

Tips for manipulating rows in HTML using jQuery when the id attribute is added

Apologies in advance for any language errors in my explanation I am working on an input table where each row has a unique ID, and the input in each row affects the next row. As new rows are added, I have implemented an incremental numbering system for the ...

The regular expression for validating credit card numbers is invalid due to a repetition error

Here is the regular expression I've been using to validate credit card numbers in JavaScript: var match = /^(?:(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|?(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])?[0-9]{11})|((?:2131|1800 ...

distinguishing the container component from the presentational component within react native

I just started developing apps using React Native and implemented a basic login function with the view and login logic on the same page named HomeScreen.js. However, after reading some articles online, I learned that it's recommended to separate the l ...

The character is having trouble displaying correctly in the ajax response

I've been searching for solutions but nothing seems to help. The issue I'm facing is with reading characters from an AJAX response. How can I properly read characters that are coming from an AJAX response in the form of a JSON object? ["label" ...

Using Ember's transitionTo method and setting a controller attribute within a callback

I am working with Ember code to transition to a specific route while also setting controllerAttr1 on 'my.route' Upon transitioning to "my.route" using this.get('router').transitionTo("my.route"), I have set up a callback function that ...

What is causing me to receive a Request Method of "GET" instead of "POST"?

I recently implemented the dropzone js library for uploading images and have a query regarding it. Is the POST method more suitable than GET when uploading an image? If yes, how can I rectify this? $(document).ready(function() { var myDropzone = new Dr ...

Non-reactive arrays in Vue.js

I am facing an issue. Here is the problem: data: { tracks: [] } The tracks array will contain a complex object. I want to achieve reactivity when assigning a new value to tracks nested object, but I do not need deep reactivity for the object. ...

Prisma encountered an error with the database string: Invalid MongoDB connection string

I'm encountering an issue with my MongoDB data provider, as I am informed that my connection string is invalid. The specific error message states: The provided database string is invalid. MongoDB connection string error: Missing delimiting slash betw ...

Getting the Featured Image from a Post Link in Wordpress: A Step-by-Step Guide

For my Wordpress project, I have a group of links leading to inner pages, each with their own featured image. These links are created using the menu feature in Wordpress. My goal is to allow users to click on these links and have the featured image from t ...

Adding query parameters dynamically in Vue without refreshing the component

I'm attempting to update the Query Parameters in Vue without refreshing the component using Vue-Router. However, when I use the code below, it forces a component reload: this.$router.replace({query: this.filters}); Is there a way to prevent the comp ...

The double click functionality does not seem to be functioning within the Backbone View

I am trying to detect double click event within a Backbone view var HomePage = Backbone.View.extend({ initialize: function(){ this.render(); }, render: function(){ var template = _.template($('#app1').html()); ...

ajaxform is not providing the correct response

There is a form below that logs into Instagram based on the response it receives. If the login is successful (returns "ok"), then it shows success, otherwise it should display an error state. However, in my case, it always returns a null state for some un ...

Tips for efficiently saving data using await in Mongoose

Currently, the code above is functional, but I am interested in utilizing only async/await for better readability. So, my query is: How can I convert cat.save().then(() => console.log('Saved in db')); to utilize await instead? The purpose of ...

Generating a Transform stream with ExcelJS to produce xlsx files

Currently, I am utilizing the ExcelJS module and creating a wrapper to suit my specific needs. This wrapper implements the Transform Stream API, and surprisingly, the node version being used is 0.10.40. The ExcelJS module offers a stream API, and based on ...

How to organize PHP JSON data using JavaScript

I need help sorting PHP JSON data from a multidimensional array using JavaScript or jQuery. Here is my PHP code: $array = array(); $x = 0; while($row = $get_images->fetch_assoc()){ $name = $row['name']; $image_type = $row['image_ ...

What is the best way to disable the click function for <a> tags that have a specific class?

I am dealing with parent navigation items that have children, and I want to prevent the parent items from being clickable. Here is an example of how they currently look: <a href="parent">Parent Item</a> Is there a way to select the <a> ...