JavaScript: Retrieve an array that is both unique and sorted

I have an array that contains duplicate items. My goal is to filter out these duplicates and return only the unique items, sorted based on their frequency of occurrence in the initial array.

const initialArr = [
  {
    id: 1
  },
  {
    id: 1
  }, 
  {
    id: 2
  },
  {
    id: 1
  },
  {
    id: 3
  },
  {
    id: 3
  },
];

const expectedSortedResult = [
  {
    id: 1
  },
  {
    id: 3
  },
  {
    id: 2
  }
]

Answer №1

Make sure to always share your attempt, regardless of how close you are to finding the solution.

It's recommended that you do some research on the following methods (which were used in solving this):

To reduce the array (create object, groupBy, and create a __count property), check out: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

After that, convert it back to an array using Object.values(), and then:

To sort the array based on the __count property, refer to: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

If you wish to remove the count property from the final output, utilize Map as shown here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

const initialArr = [
  {id: 1},
  {id: 1}, 
  {id: 2},
  {id: 1},
  {id: 3},
  {id: 3},
];

const output = Object.values(initialArr.reduce((aggObj, item) => {      
  if (aggObj[item.id]){
    aggObj[item.id].__count += 1
  }
  else{
    aggObj[item.id] = item;
    aggObj[item.id].__count = 1
  }      
  return aggObj;
}, {}))
      .sort((a,b) => b.__count - a.__count)
      .map(a => {delete a.__count; return a});
      
      
console.log(output);
.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

Integrate CKEditor with elFinder to allow for direct file uploads

I am utilizing the elFinder Laravel package for file management with CKEditor. I have followed all the steps and everything is working fine except for one issue. When I click on the image button in CKEditor to select or upload an image, after selecting an ...

Tips for accessing a variable located in a different directory

I'm facing some confusion regarding creating a global variable that can be accessed in another file. Currently, I have a chat and login folder setup. Within the login folder, there are three possible users to choose from. When a user clicks on one of ...

Incorporate a new node module into your Ember CLI application

I am interested in integrating the Node.js module https://www.npmjs.com/package/remarkable-regexp into my Ember-CLI project. Can someone guide me on how to make it accessible within the Ember application? I attempted to do so by including the following c ...

Passing a value from the Trigger button to the Modal button in Angular-UI Bootstrap

Seeking some help. I am working with angular-ui-bootstrap alongside php and mysql. My goal is to pass a value from a list of links (dynamically generated from php mysql) to a modal button each time the modal is loaded. HTML // The link below is generated ...

What is the Typescript definition of a module that acts as a function and includes namespaces?

I'm currently working on creating a *.d.ts file for the react-grid-layout library. The library's index.js file reveals that it exports a function - ReactGridLayout, which is a subclass of React.Component: // react-grid-layout/index.js module.exp ...

Is it possible to transfer 2-dimensional arrays between functions in C?

I am currently working on a project that involves creating a grid with blank spaces and randomly placing 'x' characters within it. I have successfully achieved this, but I am now facing difficulty in creating a separate function to print out the ...

A discrepancy has arisen as the value within the array structure is being altered

I am facing an issue with the array structure of an object in my Angular front-end code. When I add values to the array based on selection, the object looks like this: todayRates: 10 yesterdayRates: 5 to: Array(1) 0: [3] length: 1 __proto__: Array(0) __pro ...

How is it possible for the output to be a string array when the variable was declared as a number in TypeScript?

Snippet: function sampleFunction(sample:string|number|string[]) { if(typeof sample == "string") { console.log("Sample is String " + sample); } else if(typeof sample == "number") { console.log("Sample is Number " + sampl ...

The ViewChild instance is currently undefined

Within my component, I have the following setup: @ViewChild('PaginatedTableComponent') userTable: PaginatedTableComponent; Here is the corresponding HTML code inside the component: <pag-paginated-table #userTable [(shouldUpdate)]="sh ...

The requested resource at http://js:port/socket.io/1/ could not be located (Error 404

Having trouble connecting with Socket.io. This is the server-side code: function chatserver(){ var express = require('express'), app = express(), server = require('http').createServer(app).listen(app.get('port'),function ...

Creating duplicates of elements and generating unique IDs dynamically

I'm in the process of cloning some form elements and I need to generate dynamic IDs for them so that I can access their content later on. However, I'm not well-versed in Jquery/Javascript and could use some guidance. Here's a snippet of my ...

Getting POST data in Next.js is a common task that requires understanding of how the

I am currently working on a form validation project using the App Router within Next.js. // app/register/page.tsx export default function Register(context: any) { console.log("Register page", context.params, context.searchParams); return ...

Hover effect for changing image source not functioning as anticipated

I'm having issues creating an image that plays a GIF on hover. I came across some jQuery code on this website that should work, but it's not working for me. Any thoughts on what the problem might be? Here is the HTML and JavaScript code: $(doc ...

What is the best way to assign attributes to multiple HTML elements using an array?

Seeking assistance to hide various sections in my HTML file upon button click, with the exception of one specific section. Encountered an error message: Uncaught TypeError: arr[i].setAttribute is not a function Here's a snippet of my code: const hide ...

After submitting the form, I must only deactivate the checkbox that has been selected

Here is the HTML code I am working with: I have multiple checkboxes designed as buttons to select a room, but it's quite annoying when they all get selected at once. $("form").submit(function() { $('.seat input:checkbox').prop("disable ...

Tips for reducing image file size using ImageMinimizerWebpackPlugin in Next.js (webpack 5)

When attempting to use this plugin for image compression, I am encountering an issue where the build process completes successfully, but the images remain uncompressed. As a beginner with webpack, I'm unsure of what might be causing this problem. Cou ...

Updating the state triggers a re-render in function components

Within this element is an attempt to switch between Celsius and Fahrenheit. There are two functions that handle this conversion and store it in the state. Upon clicking onToggleToFahrenheit, the function performs as expected, but clicking on onToggleToCels ...

What error am I making in the Date calculator for the select box using Javascript/jQuery?

$(.dateselboxes) .change( function(){ var y; y=$("#year").val(); var m; m=$("#month").val(); var d; // check for leap year var isLeapYear; if(y%4==0) { if(y%100==0) { if(y%400==0) {isLeapYear=true;} else {isLeapYear=false;} } ...

When running Rollup, a syntax error occurs due to the use of the "import" syntax in an internal Rollup file using Javascript

I am working on a nodeJS/express application with a rollup bundler. My rollup configuration file defines a command in the package.json like this: "build": "env ROLLUP_OPTIONS='prod' rollup --config configs/rollup.config.js". However, when I run " ...

The pagination feature in DataTable does not retain the edited page after making changes

I have been encountering an issue while using DataTable serverside processing. My datatable includes an edit column, and when the edit link is clicked, a jQuery dialog box appears. After submitting the dialog box, an ajax.reload call is made. However, the ...