What steps can be taken to enhance the functionality of this?

Exploring ways to enhance the functionality of JavaScript using the underscore library. Any ideas on how to elevate this code from imperative to more functional programming?

In the provided array, the first value in each pair represents a "bucket" and the second value is an item. The goal is to iterate through this data and generate a list of unique items in each bucket.

var data = [
  ['A',1],
  ['A',1],
  ['A',1],
  ['A',2],
  ['B',1],
  ['B',2],
  ['B',2],
  ['B',4],
  ['C',6],
  ['D',5]
];

// Expected output:
// {
//    A: [1,2],
//    B: [1,2,4],
//    C: [6],
//    D: [5]
// }

_.chain(data)
 .groupBy(function (pair) {
    var bucket = pair[0];
    return bucket;
 })
 .mapObject(function (values, key) {
    var result = _.chain(values)
                   .map(function (pair) {
                     return pair[1]
                   })
                   .uniq()
                   .value();
    return result;
 })
 .value();

Answer №1

_.transform(x, function(accumulator, item){
  var name = item[0], age = item[1];
  var group = accumulator[name] = accumulator[name] || [];
  if (!_.includes(group, age)) group.push(age);
  return accumulator;
}, {});

Answer №2

Have you considered trying a solution similar to the following:

const groups = _.groupBy(arrayToGroup, 'key');

const result = _.mapObject(groups, function(group){
    return _.uniq(_.pluck(group, 'value'));
});

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 Angular capable of displaying a date within a specific timeframe using ng-show?

So I have a button that, when clicked, displays a list of data. I am adding a unique font awesome icon in there if the JSON key value exists. However, here lies the issue. The particular key happens to be a date. I need my ng-show function to check whether ...

The Angular Material md-input-container consumes a significant amount of space

Currently, I am exploring a sample in Angular Material. It appears that the md-input-container tag is taking up a substantial amount of space by default. The output is shown below: However, I have come across the md-input-content tag, which occupies less ...

Activate the timepicker in Bootstrap when the user clicks on the input field

Struggling to implement a timepicker feature? Look no further than this resource. After adding the necessary js and css to your project, you may encounter issues with the popup not appearing when clicked. The code provided offers a TextBox control with s ...

Updating model/schema dynamically within Express Router

My express server handles api calls by directing them to specific routes. app.use('/api/data01', require('./routes/dataRoute01')) app.use('/api/data02', require('./routes/dataRoute02')) app.use('/api/data03&apo ...

Choosing an element beneath a table row using a different element as a reference

I'm attempting to identify the checkboxes associated with the link containing delete.jpg. Here's what I've tried so far: <table> <tr class="odd"> <td><input id="cbox1" type="checkbox"></input></td> ...

What methods can I use to toggle between different divs using navigation buttons?

There are 4 divs on my webpage that I need to toggle between using the up and down arrows. Despite trying an if else statement, it doesn't work as intended. <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.c ...

Tips for handling an incorrect date entry when a field loses focus in AngularJS

If I have an <input> field with the type='date' attribute in its untouched state, it displays mm/dd/yyyy as the date format. I am looking to see if there is a way to utilize AngularJS ng-blur directive to reset the field to this original fo ...

Unchanging Dive Field

I'm having trouble understanding why this field isn't updating with the correct number. It seems that any value less than 1 is being rounded in the alert() function. I believe all numbers are simply getting rounded down, but I'm unsure of an ...

The output of the incorrect .bind() example is not as

I recently came across the .bind() method while learning JavaScript. The example I found on MDN here was quite helpful, but I decided to add some console.log() statements for better understanding. this.x = 9; // Here 'this' refers to the glob ...

Switching from PHP to JavaScript before returning to PHP to establish and manage sessions

Currently, I am in the process of resolving an issue I am facing. The problem arises when utilizing the following code for someone trying to sign into the admin panel: <script> function myFunction() { //alert('you can type now, end ...

Determining if the current URL in NextJS is the homepage

Just getting started with NextJS. I am trying to determine if the current URL is the home page. When I use: import { useRouter } from "next/router"; const router = useRouter(); const is_home = (router.pathname === ''); An error pops ...

Using v-for with nested objects

Have you been attempting to create a v-for loop on the child elements of the {song: "xxx"} object within the songs array? export const data = [ {id: "1", albumname: "xx", artist: "xxxx", dateadded: "xxxx", route: "xxxx", songs: [{ song : &apos ...

Tips on concealing all classes except one through touch swiping

If you have a website with a single large article divided into multiple sections categorized as Title, Book1, Book2, & Book3, and you want to implement a swipe functionality where only one section is displayed at a time, you may encounter some issues. ...

Populate a bootstrap-select dropdown menu with an array of choices

After creating a table using datatables and adding an empty dropdown select on the footer with Bootstrap-select, here is the code snippet: <tfoot> <tr> <th><select class="selectpicker" multiple></select>< ...

Receiving a null value when attempting to access the ids of dynamically created HTML elements using JavaScript

Encountering issue with accessing ids of dynamically generated HTML elements using javascript In my current project, I am attempting to dynamically alter the ids of div elements and remove buttons that are appended to the parent div. The desired functiona ...

Guide in activating popup notification upon form submission in React with the help of React Router navigate hook

I'm facing a challenge in triggering a success pop-up notification after submitting a form in React. The issue arises when the page redirects to a different location using React Router's useNavigate() hook, as there is no direct connection betwee ...

Avoid triggering child states in ui-router

Here is the progress I have made with ui-router states: $stateProvider .state('tools', { url: '/tools/:tool', template: '<div ui-view=""></div>', abstract: true, onEnter: function ($stateParams, ...

Troubleshooting React on an Apache Server: A Comprehensive Guide

An interactive React application utilizing React Router has been successfully deployed on an Apache server. After making modifications to the .htaccess file, most of the routes function correctly as intended. Some specific routes within the app rely on us ...

Can we pass a search term parameter to getServerSideProps in Next.js?

I've been working on a project to organize all my notes and summaries in one place. The notes are stored as markdown files, converted to HTML dynamically in the backend (it's functioning well). Now, I want to add a search feature on the notes p ...

The issue with the jQuery class change not being triggered in Internet Explorer seems to be isolated, as Chrome and

This little jQuery script I have is supposed to show a fixed navigation menu once the page has been scrolled below 200px, and then change the class on each menu list item to "current" when that section reaches the top of the viewport. The issue is that th ...