How can you implement the functionality of Lodash's _.countBy using just ES6?

Consider the following array of arrays

const data = [[150, 1], [300, 2], [430, 1]]

If I were to use Lodash's countBy, I could achieve the same result with ES6 syntax by writing

{ ...data.reduce((acc, row) => ({ ...acc, [row[1]]: (acc[row[1]] || 0) + 1 }), {}) }
. This will count the occurrences and store them in an object. How would you accomplish this using vanilla ES6 javascript?

Answer №1

Using map reduce makes this task sound quite simple. The provided function takes an array and a selector parameter as input. The selector parameter is utilized in the map function to fetch the items for counting. With reduce, we can aggregate the results by initializing an empty object and incrementing the value for each key on every iteration.

function countBy(ary, selector) {
  return ary.map(selector)
    .reduce((acc, cur) => { acc[cur] = (acc[cur] || 0) + 1; return acc; } ,{});
    // Alternatively use spread operator:
    // .reduce((acc, cur) => ({ ...acc, [cur]: (acc[cur] || 0) + 1 }) ,{});
}
// See console.log for the outcome
console.log(countBy([[150, 1], [300, 2], [430, 1]], x => x[1]));

Answer №2

To create a counting function that utilizes a simple loop, one can retrieve the key by invoking a callback and then assigning key/value pairs to an object:

function generateCount(data, getKey) {
    let count = {};
    for (let item of data) {
        let key = getKey(item);
        count[key] = (count[key] || 0) + 1;
    }
    return count;
}

const data = [[150, 1], [300, 2], [430, 1]]
console.log(generateCount(data, element => element[1]));

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

A function that can retrieve distinct values for a specific property within an array of objects while maintaining their original order

Here is some information I have: $scope.Reports = [ { Id: 1, Name: 'Report One', Year: 2016, Month: 5 }, { Id: 2, Name: 'Report Core', Year: 2016, Month: 5 }, { Id: 3, Name: 'Report Alpha', Year: 2016, Month: 3 }, { I ...

Tips for selecting 'module' over 'main' in package.json

I have developed several npm modules and compiled them in two ways: commonJS (using exports.default =) and esm (using export default) In my package.json, I have specified the main file as index.cjs.js and the module file as index.esm.js. However, when ...

Tips for maximizing efficiency and minimizing the use of switch conditions in JavaScript when multiple function calls are needed

After coming up with this code a few minutes ago, I began to ponder if there was a more elegant way to optimize it and condense it into fewer lines. It would be even better if we could find a solution that eliminates the need for the switch condition altog ...

Steps for removing an element from an array using Mongoose and Node.js

After reading and attempting to implement the solutions provided by others, I am still struggling to understand why it's not working for me. This is my first project involving backend development. While progressing through a course, I decided to work ...

An effective way to prevent right-clicking on iframes across all websites

I am facing an issue with disabling right click for the iframe. I've successfully disabled it for the default URL of the IFrame, but when displaying any other webpage, the right click remains usable. Below are the sample codes I have used: document.o ...

Generating matrices in MATLAB

Is there a way to create an array in Matlab that allows me to store multiple user inputs without replacing the previous ones? As a beginner, I appreciate your patience with me. Thank you! ...

Display a hoverable button for a singular element within an array during the process of mapping through the array

const ChatWidget = () => { const bodyRef = useRef(null) const [{messages,roomMessages,roomID,socket,user}, dispatch] = useStateValue() const [dropdown, setDropdown] = useState(false) useEffect(()=>{ const setScreen = () =>{ bodyRef.cur ...

The PrimeNG checkbox is not reflecting the updated ngModel changes in the view

I'm dealing with a list of PrimeNG checkboxes that are connected to an array named selectedItems through the ngModel directive. Initially, I have some items already checked in this array. The tricky part is that I need to add items to the selectedItem ...

Connecting a JavaScript variable

Is it possible to include a JavaScript variable in a link? I've tried the code below but it just shows a blank page. The viewData.php file will contain PHP GET Variables used to retrieve data based on the period and type, which determine whether renta ...

The C# counterpart to the JavaScript "OR assignment" concept

Is there a comparable feature in C# to JavaScript's assignment syntax var x = y || z;? This operation does not result in true/false. If y is defined, it assigns that value to x, otherwise it assigns z to x, even if it is undefined. Keep in mind, in J ...

Developing a webpage that navigates seamlessly without the hassle of constantly refreshing with

I am in the process of creating a website that is designed to run everything within the same file, but I am unsure about how to locate study materials for this project. For example: In a typical website scenario -> If I am on index.php and I click on ...

I am facing an issue with saving my file on Heroku using Node.js. However, the file is being saved successfully on the local file system

I am currently developing a basic file uploader application using Nodejs. The files are being successfully saved to the local storage in an 'upload' directory, but after deploying the app to Heroku, I encountered an error as shown in this https:/ ...

The outcome of the Ajax response is not in accordance with my expectations

Whenever the response from my PHP echo statement in an AJAX request is "loggedIn", I want to invoke the displayUsers function. However, it seems to always skip executing displayUsers() and goes straight to the else statement. Oddly enough, when I alert the ...

I'm having difficulty implementing a vue-awesome icon on my project

I am attempting to utilize the standard window-close icon from vue-awesome. I have imported my vue-awesome using the following code: import 'vue-awesome/icons'; import Icon from 'vue-awesome/components/Icon.vue'; Vue.component('i ...

Tips for dynamically assigning unique IDs to HTML form elements created within a JavaScript loop

let count = 0; while (count < 4) { $('#container').append("<div><input type='textbox' class ='left' id='left-${count}'/><input type='textbox' class ='right' id=' ...

Is it possible to use an Array as a key in a Hash in Perl 6?

While browsing through the Hash documentation, I came across the section discussing Object keys, which led me to believe that any type could be used as a Hash key with proper indication. However, I encountered an issue when attempting to use an array as th ...

Tips on storing the amount of time a user devotes to answering questions on my form into a database

I am facing an issue with storing the "duration" in my database. The "duration" I aim to store is the time spent by the user answering a question I created. When they click the submit button, I want to save the duration they spent in the database. Below i ...

What is the best way to create a dynamic URL linking to an external site in Angular 5?

When attempting to create a link like this: <a [href]="getUrl()">click me</a> getUrl() { return this.domSanitizer.bypassSecurityTrustUrl('http://sampleUrl.com'); } The link is not clickable. When hovering over the ...

Custom time selector does not automatically set the default value

After creating two inputs where one represents hours and the other minutes, clicking on edit should display the total time in seconds. The original time for editing should remain unchanged until you choose to save it. Here is the link to the code: https:// ...

Navigating through a series of items in VueJS can be easily accomplished by using a

Below is the Vue instance I have created: new Vue({ el: '#app', data: { showPerson: true, persons: [ {id: 1, name: 'Alice'}, {id: 2, name: 'Barbara'}, {id: 3, name: &a ...