Looking to loop over an array to extract certain key-value pairs and append them to an empty object

So here's the challenge: create a function that takes an array of strings and outputs an object. The keys in the object should represent the number of characters in each string, while the values should indicate how many times a string with that amount of characters appears.

I hit a roadblock while working on this problem and could really use some assistance. I've tried every search engine query I can think of but haven't had any luck so far. Any help you can provide would be greatly appreciated!

The expected output should resemble this example: characterCount(['apple', 'berry', 'cherry']) // {5:2, 6:1}

function characterCount(arr){

  var newObj = {};
  var valueMax = 0;
  var currentValue = 0;

  for(var i=0; i < arr.length; i++){
    var key = arr[i].length;
    for(var z=0; z < arr.length; z++){
      if (arr[z].length === arr[i].length){
        currentValue ++;
        if (currentValue > valueMax){
          valueMax = currentValue;
        }
      }
    }
    newObj.key = "valueMax";
  }
  return newObj;
}

Answer №1

Check out the Array.prototype.reduce method. It allows you to loop through an array, process each value, and produce a single result.

function countCharacters(arr) {
  return arr.reduce((counts, str) => ({
    ...counts,
    [str.length]: (counts[str.length] || 0) + 1
  }), {});
}

const charCounts = countCharacters(['apple', 'berry', 'cherry']);
console.log(charCounts);

Another option is to use Object.assign instead of using the spread operator to merge objects in the accumulator.

function countCharacters(arr) {
  return arr.reduce((counts, str) => Object.assign(counts, {
    [str.length]: (counts[str.length] || 0) + 1
  }), {});
}

const charCounts = countCharacters(['apple', 'berry', 'cherry']);
console.log(charCounts);

Answer №2

One way to achieve the desired output is by utilizing the reduce method on the array.

function countCharacters( arr ) {
  return arr.reduce( (agg, current) => {
    // determine length of current item
    const length = current.length;
    // increment value at key index by one (initialize with 0 if it doesn't exist)
    agg[length] = (agg[length] || 0) + 1;
    // return updated object for next iteration
    return agg;
  }, {});
}

console.log( countCharacters(['apple', 'berry', 'cherry']) );

Answer №3

While using reduce may be considered more efficient, this code offers a simpler alternative.

function countCharacters(arr) {
  const charactersByLength = {};
  
  for (let item of arr) {
    charactersByLength[item.length] = (charactersByLength[item.length] || 0) + 1;
  }
  
  return charactersByLength;
}

console.log(countCharacters(['apple', 'berry', 'cherry']));

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

By clicking, dynamically add unique classes along with incrementing numerical values

I have a span tag and a button tag <span class="myspan">1</span> <button id="add">Add +1</button> var arr=["myspan1","myspan2","myspan3","myspan4"} In order to add more span tags with new classes from the array and increase the v ...

Generating and graphing an array based on the values of a separate array in Python

As a beginner in programming, I am new to Python and have only been using it intensively for the past few weeks. However, I need it for my application in statistics where I am attempting to achieve the following: I want to generate an array of integers N ...

Tips for successfully submitting a text string from an input box with type="number" attribute

Is there a way to send the value displayed in an HTML input box as '030.34' rather than '0.34'? I am looking to add '03' at the beginning for identification purposes. The input box must be of type 'number' to enable ...

Efficiently transfer the array elements by cutting and pasting

While I am aware that $pull and $push can be used to update array elements in mongodb, I am interested in cutting an element and pasting it to a different index. To illustrate my question, consider the following scenarios: Scenario 1 Starting with the ...

What is the best way to store all content from elements into an array with jQuery?

<div id="main"> <p>Content1</p> <p>Content2</p> <p>Content3</p> </di> Output should look like this : ["content1","content2","content3"] ...

Ways to assign a value to an input element in AngularJS without impacting its ngModel

JAVASCRIPT: .directive('search', [function () { return { restrict: 'A', link: function (scope, element, attrs) { attrs.$set('placeholder', 'Word...'); console.log(attrs); ...

CUDA.jl encountered an error: The method `fillpixel!` does not support the data type `CuDeviceMatrix{RGB{Float32}, 1}`

After creating a basic ray tracer in Julia, I decided to work on a faster version using CUDA. Although I can't share the entire code here, I believe this snippet is crucial for addressing my issue: world = World(RGB(1, 1, 1), 5e-6, shapes, lights, 0.2 ...

Exploring the Differences in Site Navigation: PHP/HTML, Ajax, and CSS/Javascript

Lately, I've been weighing the pros and cons of using AJAX for my website navigation to transfer only necessary updated HTML elements. Alternatively, if there isn't a significant difference between new elements and current ones, just loading the ...

The API response displayed in the browser does not match the one generated in the code

Here is a snippet of my code: async function BuiltWithCall(website) { var domainCall = `https://api.builtwith.com/v12/api.json?KEY=${keys.builtWith}&LOOKUP=${website}`; var domainRes = await fetch(domainCall); console.log(domainRes); v ...

Is it effective to cancel a $timeout within the 'then' function?

I find myself doing this quite frequently, but I'm unsure if it's actually effective. How can I verify that it's working as intended? And if it's not, what is a more reliable way to cancel a timeout after it has finished? var delay = $ ...

In PHP, use the json_decode function to extract a particular value from an object that is nested within an array, which

Currently, I am in possession of this JSON data: {"id":"***hidden***","event_version":"1.0",... When breaking down the structure, it follows this pattern: { "id":"***hidden***", "event_versi ...

What could be causing the div to not respond to ngAnimate?

Recently, I encountered an issue with adding animations to a list of <div>'s in my webapp. After incorporating ngAnimate into the app.js file and including ng-animate="'animate'" in the <div>, I was disappointed to find that the ...

To include a request parameter in every HTTP request made with $http in AngularJS

I am looking to utilize Angular's $http service to communicate with an API. However, I need to find a way to save my authorization token within $http so that it is included in every request, whether it is a post, get, put, or delete request. I have ob ...

Arranging Data: Processing Files with Input/Output

I've been trying to figure out how to sort an Array, but I keep running into some error messages that I don't quite understand. The errors I'm receiving are: [WARNING name lookup of 'index' changed. matches this 'char* index ...

Creating an interactive map on WordPress: A step-by-step guide

I have successfully created a clickable image on Codepen <div style="width: 1000px; height: 993.73px;"> <img src="https://www.dyfedarchaeology.org.uk/wp/wp-content/uploads/Testmap.svg" alt=&q ...

Can ag-grid in react allow for the application of several filters on one column simultaneously?

I would like to personalize the agSetColumnFilter and incorporate the agNumberColumnFilter feature into it. What steps should I take to make this happen? ...

Guide on how to utilize JavaScript to redirect to a URL for PUT or POST requests by clicking a button

I have a button <button class="delivery-orders-button" onclick="markDone(${order.order_id})">Dispatch order</button> and my goal is to have the markDone function redirect the user to a designated page, similar to how forms ...

In Express JS, the REST API encounters an issue where req.body is not defined

I am currently working on building a REST API with Express JS. When I use console.log(req.body), it is returning undefined as the output. Below is the code snippet from my routes.js file: const express = require('express'); const router = expres ...

How can I use the *ngFor directive in Angular 2 or Ionic applications?

I am currently working on an Ionic Project. Upon button click, a request is processed and data is received as shown below: public login() { //this.showLoading() var test33; this.auth.login(this.registerCredentials).subscribe(data => { ...

Express routes are malfunctioning

I have a situation with two different routes: /emails and /eamils/:id: function createRouter() { let router = express.Router(); router.route('/emails/:id').get((req, res) => { console.log('Route for get /emails/id'); }); ...