Is there a way for me to locate anagrams within a collection of words?

I'm attempting to find all anagrams in an array of words:

arr = ['cab','bac','tru']

The expected result should be:

{abc: ['cab','bac']}

Here's the code I've tried so far:

var words = ['cab', 'bac', 'mihir']
let result = {}

words.forEach(word => {
  var a = word.split("").sort().join("");
  result[word] = a

})

console.log(result)

Is there a way to loop through the values to access keys with identical values?

Answer №1

To organize the words alphabetically, you can use a method where the sorted words serve as keys in an object. Each word that matches the key is then collected in an array:

var words = ['cab', 'bac', 'mihir']
let result = {}

for (const word of words) {
  const sorted = word.split("").sort().join("");

  if (sorted in result) {
    // Add the word to the existing entry in the result
    result[sorted].push(word);
  } else {
    // Create a new entry for the word
    result[sorted] = [word];
  }
}

console.log(result);

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

Is it possible to maintain inline style modifications when the dispatch event is triggered?

I am encountering an issue with inline style changes that are reset once my dispatch function is completed. Even though the rest of my component's functionality is working fine (the counter continues to run), the state is being re-rendered. Here is a ...

Save the array as a variable in your JavaScript code so that you can easily access it

I am currently working on generating a list only when a specific page is visited using JS/jQuery. I then need to be able to access this list when navigating to other pages and retrieve the variables within it. How can I effectively store this list? Initia ...

Jest - verifying the invocation of local storage within an async function that is currently being mocked

I need assistance with testing an API call within a React component. The current setup involves setting localStorage in the api call, which is causing issues when trying to test if it's being called correctly. login = () => { // <--- If I se ...

Creating a JavaScript class definition without the need for instantiation

I am looking to create an empty data class in JavaScript that can later be filled with JSON data. In C#, I would typically do something like this: class Person { string name; int age; Person[] children; var whatever; } However, when I try ...

How can I send a file to AWS S3 using a signed URL with cordova-plugin-file-transfer?

I have successfully uploaded to S3 using a file picker and regular XMLHttpRequest, but I'm struggling to achieve the same with the cordova file transfer plugin. I suspect that the issue lies in the plugin not generating the correct signable request o ...

Utilizing Anglar 16's MatTable trackBy feature on FormGroup for identifying unaltered fields

In my application, I am working with a MatTable that has a datasource consisting of AbstractControls (FormGroups) to create an editable table. At the end of each row, there are action buttons for saving or deleting the elements. My goal is to implement tr ...

Deselect a selected radio button by clicking on it

I am trying to create a radio button with an unchecked value, and I thought this code would work: $('form').on('click', 'input[type="radio"]:checked', function (event) { $(this).prop("checked", false); }); It seems simpl ...

Trouble arises when trying to define the style for an element generated through the Document

I'm having trouble setting the style for a 'tr' element created using DOM within JavaScript. Here's the code snippet: var tr = document.createElement("tr"); tr.onmouseover=function(){this.style.backgroundColor='#fbf9e0';}; ...

I am facing difficulties with invoking the popOpen() function within my parameters in JS, HTML, and CSS

I'm currently facing an issue with my code. I am attempting to invoke my openPop() function with the input parameter 'pop' within some of my sensor code, but no pop-up is appearing even though I believe I am calling the popup correctly. If a ...

Instead of modifying the selected class, jQuery generates inline styles

Utilizing the following code to dynamically create a class: $("head").append('<style type="text/css"></style>'); var newStyleElement = $("head").children(':last'); newStyleElement.html('.move{transform: translateX(1 ...

Discover the process of retrieving all workday dates using Angular

Currently, I am working on a project in Angular that involves allowing employees to record their work hours. However, I am facing a challenge in figuring out how to gather all the work dates and store them in an array. Here is what I have attempted so fa ...

"Creating a user-friendly time selection feature similar to Google Analytics in

Does anyone know of a time range selector that functions like the draggable time line section in Google Analytics? Google offers a time line selection feature using three blocks, which can be replicated with Jquery UI and other methods. However, achieving ...

Some filters in Bootstrap table not displaying properly

I've been struggling to showcase this bootstrap table with the data-filter-control attribute, but I'm unable to achieve it successfully. The filters are failing in two main ways: The filter is not showing all the categories from that column The ...

Explanation of stdout and stderr in a child process using node.js version 8

I'm encountering an issue while attempting to initiate a child process in my node dev-server in order to configure the API json-server before launching it using the command: nom run dev -- reset The problem lies in the fact that the stdout and stder ...

transferring information back and forth between a javascript array and php

Currently, I am developing a design website that allows users to create designs on an HTML5 canvas and save them on the server. All user information is stored in a MySQL database, while the designs are saved in a JavaScript array. My goal is to seamlessly ...

What could be causing the issue with this basic THREE.js javascript particle system?

{/*I'm not sure if there are any errors in this code. I'm using the latest version of Chrome for testing purposes. Previously, I created a similar program that displayed a wireframe cube without any issues. It ran smoothly at that time. However, ...

Encountered an error when creating my own AngularJS module: Unable to instantiate

Attempting to dive into TypeScript and AngularJS, I encountered a perplexing error after following a tutorial for just a few lines. It appears that there may be an issue with my mydModule? angular.js:68 Uncaught Error: [$injector:modulerr] Failed to inst ...

When scrolling on an IOS mobile device, the .on(click) event is triggered for fixed position elements

Whenever I click on an li element or menu, a function is triggered that moves the nav container to the left by the width of the window. However, on my iPhone, after I click to slide the container off the screen, the event gets triggered repeatedly every ti ...

Looking to verify a disabled select element and adjust the opacity of that element when it is disabled

$_product = $this->getProduct(); $_attributes = Mage::helper('core')->decorateArray($this->getAllowAttributes()); ?> <?php if ($_product->isSaleable() && count($_attributes)):?> <dl> <?php foreach($_attrib ...

Unable to successfully remove item by ID from mongoDB within a Next.js application

Currently, I am developing an application using NextJS for practice purposes. I'm facing challenges in deleting single data from the database with the findByIdAndDelete function. Error encountered: CastError: Cast to ObjectId failed for value "undef ...