A guide on tallying values in an array and organizing them into an object within a fresh array using Javascript

I have a large array filled with various words, and I am aiming to create a new array that organizes each word along with the number of times it appears as properties within an object. Here is an example:

const arrayWithWords = [`word1`, `word2`, `word5`, `word1`, `word3`, `word6`, `word2`, `word3`, `word1`, `word5`]

// Desired output:

const newArray = [ {name: `word1`, amount: 3} {name: `word2`, amount: 2} {name: `word3`, amount: 2} {name: `word4`, amount: 0} {name: `word5`, amount: 2} {name: `word6`, amount:1}]

I've attempted to solve this using a for-loop, but I always seem to encounter roadblocks. Can you suggest a potential solution to tackle this issue?

Answer №1

To find the solution, simply analyze the frequencies of each word in the given array.

const wordsArray = [
  `apple`,
  `banana`,
  `orange`,
  `apple`,
  `kiwi`,
  `grape`,
  `banana`,
  `kiwi`,
  `apple`,
  `orange`,
];

let result = wordsArray.reduce((previous, current) => {
  if (!previous[current]) previous[current] = 1;
  else previous[current] += 1;
  return previous;
}, {});

result = Object.entries(result).map((item) => ({ name: item[0], quantity: item[1] }));
console.log(result);

Answer №2

With the use of Array.prototype.reduce, it is possible to calculate the frequency of each item in an array.

const input = [`word1`, `word2`, `word5`, `word1`, `word3`, `word6`, `word2`, `word3`, `word1`, `word5`];

const groupedBy = input.reduce((acc, cur) => {
  acc[cur] ? acc[cur]['amount'] ++ : acc[cur] = {
    name: cur,
    amount: 1
  };
  return acc;
}, {});
const result = Object.values(groupedBy);
console.log(result);

Answer №3

To accomplish this task, you can convert the given array into a map and then count the occurrences of each element using the map provided below:

const wordsArray = [`apple`, `banana`, `orange`, `apple`, `grape`, `kiwi`, `banana`, `grape`, `apple`, `orange`]
let wordMap={};
wordsArray.forEach((word)=>{
    wordMap[word] = wordMap[word] ? wordMap[word] + 1 : 1;
});
const newWordArray = Object.keys(wordMap).map(key=>{
    return {name:key,count:wordMap[key]};
});
console.log(newWordArray);

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 causes the datepicker to flicker in React when an input field is in focus?

Can someone explain why the datepicker is flickering in React when focusing on the input field? I have integrated the following date picker in my demonstration: https://www.npmjs.com/package/semantic-ui-calendar-react However, it is flickering on focus, ...

The $digest method is refreshing the main $rootScope parent

I'm having trouble grasping the concept of how $digest functions. I came across a response on Angular $scope.$digest vs $scope.$apply that explains it as follows: " $digest() will update the current scope and any child scopes. $apply() will update ev ...

Navigating with React in ES5

My email addresses are "[email protected]" and "[email protected]". I am facing an issue with the following minimal example code: var React = require('react'); var ReactDOM = require('react-dom'); var Router = require(' ...

Update data in PHP dynamically without reloading the page

It would be great if they are doing well! I have encountered a minor issue - everything seems to work perfectly, but it doesn't quite meet my requirements. I am referring to this particular function: <script> var previous = null; var current = ...

Tips for saving a collection of Numpy arrays in a CSV file

I am facing a challenge with managing image data that includes names, paths, and corresponding CNN feature vectors as numpy arrays. With a large number of images, I have a list of names, paths, and vectors (each as a numpy array with dimensions (1, 2048, 1 ...

Using Javascript to iterate over an array

Issue: I am facing a challenge with updating an array containing image links. The goal is to add new image links while retaining previously uploaded images in the array. However, the problem arises when the previous image links are getting combined. See ex ...

Synchronize two div elements with JavaScript

The demonstration features two parent divs, each containing a child div! The first parent div's child div is draggable and resizable using JQueryUI. There are events for both dragEnd and resizeEnd associated with this div. The goal is to synchronize ...

transferring data from grails to javascript via a map

I am facing an issue with passing a Map object from my Grails controller to JavaScript. The code snippet in my controller is as follows: def scoreValue = new HashMap<String,String>(); scoreValue.put("0","poor"); scoreValue.put("1","good"); ... retu ...

Unable to Define Headers in Fetch GET Call

My current struggle involves sending a GET Request from the browser to my backend (which uses node + express). However, I am encountering issues with setting the headers properly. Below is the code snippet from the frontend: let accessToken = localStorage ...

It is not possible to submit two forms at once with only one button click without relying on JQuery

I need to figure out a way to submit two forms using a single button in next.js without relying on document.getElementById. The approach I've taken involves having two form tags and then capturing their data in two separate objects. My goal is to hav ...

Error encountered in NextJS: Trying to call res.unstable_revalidate which is not a function

I recently tried out a cutting-edge feature introduced in NextJS v.12.1 . The API itself is functioning correctly and can be accessed. However, I encountered a 500 error with the message res.unstable_revalidate is not a function. This issue persisted wheth ...

Disable button with Checkbox Javascript functionality

In my PHP code, I have an array of users that I pass to the view (in Laravel) and use a foreach loop to display all users in a table. Everything is working fine so far. However, I want to make a "send" button visible when a checkbox is clicked, instead of ...

What is the best way to incorporate a <c:forEach> loop into JSP operations?

I am attempting to calculate the product of two variables that are associated with an item in a loop. Below is the code snippet from the JSP file: <table> <thead> <tr> <th>PRICE</th> <th ...

Obtaining the blog slug dynamically upon clicking with ReactJS

Currently, I am developing a project using Reactjs and Nextjs. One of the tasks at hand is to obtain the "slug" value after clicking on a blog post. However, at this moment, the value returned is undefined despite trying the following code: <h4 onClic ...

Transferring information via a function to a modal component in VueJS

Seeking advice on passing data to a modal. I'm attempting to pass data to a modal, where a function within a v-for loop gathers the video URL for later opening. The modal is placed outside the v-for loop to prevent all videos from playing the same o ...

What methods can we employ to prevent the GraphQL query from being triggered with every keystroke when using React?

Recently, I received a new task that requires me to implement input value debouncing to prevent backend requests on every keystroke. Additionally, I need to establish an internal useState for CollectionsAutocomplete, which is connected to the generalQuery ...

Stop displaying AJAX requests in the console tab of Firebug, similar to how Twitter does it

I'm looking for a way to prevent my AJAX calls from being logged in Firebug's Console tab, similar to how Twitter does it. When using Twitter search, you'll see a live update feed showing "5 tweets since you searched." Twitter sends periodic ...

Error message: AngularJS Jasmine spyOn: number has no functionality

I am encountering difficulties while attempting to execute a test that utilizes a mockup for a service call (retrieving location data from a web SQL database). Below is the controller code: .controller('LocationDetailCtrl', function ($scope, $s ...

Placing buttons on top of a video within a div container

I am facing a challenge with implementing custom controls on a video embedded in my webpage. I have tried setting a div to absolute position for the buttons, but they are not clickable. Is there a way to achieve this without using jQuery? I need the butto ...

Reversing the circumstances leads to the necessary outcome in an If Else clause

Imagine a scenario where there is an array containing various events and timestamps. I am attempting to calculate the time difference between certain events based on specific conditions. The criteria for a complete event is if the previous array element&ap ...