nested distinct apartment in js

Are there any new and super powerful ES JavaScript features that can accomplish this task? (I could come up with a function to do it, but I'm curious if there's a cutting-edge ES202* technique available)

let arr = [
    ['cb', ''],
    ['cb', '34'],
    ['cb', '35'],
    ['rb', '1']
];

/*
Desired Outcome: 
[['cb', ['34', '35']], ['rb', '1']]
*/

console.log([...new Set(arr.flat(1))])

Answer №1

Consider implementing the upcoming Array#groupBy.

Alternatively, create your own polyfill.

Array.prototype.groupBy ??= function (callbackfn, thisArg) {
    const O = Object(this);
    const len = O.length >>> 0;
    if (typeof callbackfn !== 'function') throw new TypeError(callbackfn + ' is not a function');

    let k = 0;
    const groups = {};

    while (k < len) {
        const Pk = Number(k).toString();
        const kValue = O[Pk];
        const propertyKey = callbackfn.call(thisArg, kValue, Number(k), O);
        (groups[propertyKey] ??= []).push(kValue);
        ++k;
    }
    return groups;
};


const
    array = [['cb', ''], ['cb', '34'], ['cb', '35'], ['rb', '1']],
    result = Object
        .entries(array
            .filter(([, v]) => v)
            .groupBy(([k]) => k)
        )
        .map(([k, v]) => [k, v.map(([, v]) => v)]);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

UPDATE 2023

Try using Object.groupBy instead.

const
    array = [['cb', ''], ['cb', '34'], ['cb', '35'], ['rb', '1']],
    result = Object
        .entries(Object.groupBy(array.filter(([, v]) => v), ([k]) => k))
        .map(([k, v]) => [k, v.map(([, v]) => v)]);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Tips on refreshing a div using jQuery while maintaining the functionality of addEventListener

Hi, I am facing an issue with updating the "div" element. The refresh works fine, but after refreshing when I try to click on the updated "div", the addEventListener in my JavaScript code does not seem to work anymore. Can someone please explain why this i ...

Tips for utilizing the Raycaster in tandem with a CombinedCamera?

When trying to implement a Raycaster for selection, I encountered an issue where it worked fine with a PerspectiveCamera but not with a CombinedCamera. It appears that the Raycaster does not support CombinedCamera, so I made some modifications in the thre ...

Create a new function that generates a unique div element

How can I replicate this function in a different container? function goto(id, t){ // Move to the designated div id using animation $(".headbox-wrapper").animate({"left": -($(id).position().left)}, 600); // Remove the "active" class from a ...

Using JavaScript to effectively handle my JSON data

I've been trying to retrieve the data from my JSON file, but I keep getting an error in the console that says "Uncaught TypeError: Cannot read property 'longitude' of undefined." This method is new to me and I would really appreciate any hel ...

Display a message indicating no data is available if the specified text is not found within the div

In the code snippet below, there is an input element followed by a div containing multiple child elements: <input type="text" onkeyup="filter()" id="filter_data"> <div id="body"> <div class="child"> Text 1 </div> <div class ...

Is there a way to rearrange the selectpicker selection based on the user's choice?

I'm in the process of setting up a selectpicker that allows users to choose multiple options from a dropdown list. The challenge is that the values extracted by my backend need to be in the order of user selection, rather than the original order of th ...

Seamless infinite background scrolling on the canvas without any disruptions

In my HTML5/JS project, I have implemented infinite background scrolling using multiple canvases. The challenge I am facing is that while the animation is smooth after rendering, there is a quick hiccup when transitioning to the next frame due to the need ...

Issues with navigating sliders

I've encountered a problem with my slider arrows while following a YouTube tutorial. They are supposed to appear next to the picture and testimonial, but instead, they are showing up at the top. This issue wasn't present initially, but after enco ...

Encountered a network issue while making an AJAX call using the POST method along

Greetings! I am facing an issue with an ajax call using the POST method. When I execute it, it goes to the error part and returns "Network Error" or just "Error". However, when I use online tools like Advanced Rest client and Request maker (), I receive ...

Upload the image data into the input file tag

Is there a way to take a string code stored in a JavaScript variable that is retrieved from the Cropit plugin (used for cropping images) and then set this information into an input file tag? I want to be able to send it via AJAX to PHP. Here is the JavaSc ...

Creating packing features specifically designed for resolution within a reusable module

I've decided to revamp my Angular application based on John Papa's style guide (well, mostly) and my main focus is on improving modularity. The stumbling block I've encountered is with route resolves. So far, I've been using a global ap ...

How to eliminate unnecessary JSON data using JavaScript

Recently delving into the realms of JSON and JavaScript, I found myself tasked with creating a table in Cloudant NoSQL. Upon gathering Weather data from a reliable Weather Company in JSON format to upload onto Cloudant, I encountered some irrelevant data t ...

Is the size of the JSON file inhibiting successful parsing?

After retrieving a large list of schools with their respective columns from the database, totaling over 1000 rows, I converted it to JSON and passed it to my view. I then attempted to parse it using $.parseJSON('@Html.Raw(Model.subChoiceJsonString)& ...

Retrieving a condensed JSON reply from the backend Node.js to AngularJS

After receiving a JSON response from my Node.js server, I encountered a performance issue in my frontend app built with AngularJS. When the array in the response contained over 100,000 objects, the browser would hang. To address this, I decided to extrac ...

Tips for successfully passing the return values of methods to be used in the mounted lifecycle hook

click here to view image descriptionHey! I'm new around here and would really appreciate some feedback. In my code, I have a nested list called "mixed" that looks like this: [['John',34],['Mary',4],['Jack',234]]. I' ...

Freezing objects using Object.freeze and utilizing array notation within objects

Could someone kindly explain to me how this function operates? Does [taskTypes.wind.printer_3d] serve as a method for defining an object's property? Is ["windFarm"] considered an array containing just one item? Deciphering another person& ...

Unable to assign a class to the menu option

I'm encountering an issue with the following code: JavaScript $(document).ready(function() { var url = window.location; var element = $('#nav1 li a').filter(function() { return this.href == url || url.href.indexOf(this.href) == 0; ...

The audio directory is not included in the build of the Ionic framework, causing it to be skipped and absent

Recently, I've been working on an Ionic/Cordova app and came across a folder labeled /audio which consists of mp3 files: /www /assets /audio file.mp3 /css /js config.xml index.html The issue at hand is that the /audio directory is n ...

New ways to update Vue.js data without the need to bind HTML to methods

In my Vue.js application, I have a file where users can choose from different graphs by setting the activeOrderView variable through a @click event. Each graph has its own set of x-axis categories and y-axis values. The issue I am facing is that when a us ...

JavaScript does not alter the text box for the default dropdown value

My webpage has three elements: a text box named txtSubTotal, a drop-down menu named discount, and another text box called txtGrossTotal. The txtSubTotal updates when the user clicks on the 'ADD' button, while the txtGrossTotal updates based on th ...