Locate any identical elements within an array and substitute them with their corresponding frequency

Let's say I have an array that looks like this:

arr = [25, 25, 25, 20, 15, 10, 10, 5];

My goal is to count the number of duplicate values (for example, three 25s and two 10s) and create a new array that would look like this:

newArr = ['25 * 3', 20, 15, '10 * 2', 5];

What would be the most effective way to achieve this task? Your guidance is much appreciated!

Answer №1

A solution utilizing Set and filter can be implemented

let arr = [25, 25, 25, 20, 15, 10, 10, 5];

const newArr = [...new Set(arr)].map((x) => {
    const count = arr.filter(y => y == x).length
    return count > 1 ? x + " * " + count: x;
})

console.log(newArr) //  ["25 * 3", 20, 15, "10 * 2", 5]

Alternatively, if you prefer the numerical value use this method

let arr = [25, 25, 25, 20, 15, 10, 10, 5];
    const newArr = [...new Set(arr)].map((x) => arr.filter(y => y == x).length * x)
    console.log(newArr) // [75, 20, 15, 20, 5]

Answer №2

To iterate through each item of an array and keep track of how many times each item has been seen before, you can utilize the Array#forEach loop.

Here is a demonstration:

let arr = [25, 25, 25, 20, 15, 10, 10, 5];

let result = [], seenBefore = [];

arr.forEach((item) => {
  let seen = seenBefore.indexOf(item);
  if (seen !== -1) return result[seen].count++;
  result.push({ name: item, count: 1 });
  seenBefore.push(item);
});

result = result.map(({ name, count }) =>
  count > 1 ? `${name} * ${count}` : name
);

console.log(result);

Alternatively, you can achieve the same using Array#reduce:

let arr = [25, 25, 25, 20, 15, 10, 10, 5];

let result = arr
  .reduce(
    (acc, item) => {
      acc[1].indexOf(item) !== -1 ? acc[0][acc[1].indexOf(item)].count++ : (acc[0].push({ name: item, count: 1 }), acc[1].push(item));
      return acc;
    },
    [[], []]
  )[0]
  .map(({ name, count }) => (count > 1 ? `${name} * ${count}` : name));

console.log(result);

Answer №3

To efficiently handle this scenario, you can leverage the power of the reduce method. Within each iteration, compare the current element with the previous one and also consider the type of the last element present in the accumulator.

const arr = [25, 25, 25, 20, 15, 10, 10, 5];
const result = arr.reduce((r, e, i, arr) => {
  if (i && e === arr[i - 1]) {
    if (typeof r[r.length - 1] === 'number') {
      r[r.length - 1] = `${e} * 2`;
    } else {
      const [key, value] = r[r.length - 1].split(' * ')
      r[r.length - 1] = `${key} * ${+value + 1}`
    }
  } else {
    r.push(e)
  }

  return r;
}, [])

console.log(result)

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

"Having trouble finding the issue in my Angular 2 todo list that is preventing new items from showing

I am having trouble with my 'todo-list' where the new 'todo' is not being added without any errors in the console. I have checked my code in the component.ts file but cannot figure out why it's not working. Here is the code snippet ...

The getElementById function can only select one option at a time and cannot select multiple options

I'm having an issue with a JavaScript function that is supposed to allow me to select multiple options, but it's only selecting the first one. Here is the JavaScript code: function index(){ var a="${staffindex}".replace("[",""); ...

Show User-Specific Information Using DataTable

After conducting extensive research, I have been unable to find a suitable example to reference. My goal is to customize my DataTable so that it only displays data relevant to the currently logged-in user (admin accounts will have access to all data). I am ...

What is the reason behind Webpack's behavior of loading all files from a folder during lazy loading

I am attempting to dynamically import i18n files using webpack: function getI18n(lang) { return import(/* webpackChunkName "i18n/[request]" */ `./locales/${lang}.json`) .then(/*whatever*/) } However, I have noticed that all the files from the specifi ...

What is the best way to incorporate the :after pseudo-element in JavaScript code

HTML: This is my current code snippet <div class="one"> Apple </div> I am looking to dynamically add the word "juice" using JavaScript with the .style property. Is there an equivalent of :: after in CSS, where I can set the content in JavaS ...

How to make a div stand out when clicked in an Angular application

Within my code, there is a booking-list div that I am utilizing to showcase booking timings. When hovering over this div, the background-color changes, as depicted in the image below. https://i.stack.imgur.com/Iz1r6.png My current dilemma is that when se ...

Exploring the concepts of relative and absolute paths in JavaScript

I'm struggling to grasp the concept of relative and absolute paths. Can someone please help explain how they operate in relation to the directory? I have the following code but I am unable to include the PostService module. import { Component } from ...

Can React Router be integrated with Material UI tabs?

I have made some changes to the code of the Tabs component in material ui, <AppBar position="static"> <Tabs variant="fullWidth" value={value} onChange={handleChange} aria-label="nav tabs example" > < ...

Having difficulty reaching elements within a shadow frame using Selenium in Java

I am encountering an issue while trying to access an element within a shadow iframe. I am able to switch to the frame successfully, but when attempting to access elements inside it, I am getting a Stale Element Exception. Any assistance with this would be ...

The property 'x' cannot be found when declaring two different return types

Consider this example: interface Dog { name: string } const likeDog = true const getDog = (): Dog | boolean => { const val = likeDog ? { name: 'fido' } : false return val } const myComponent = (): void => { const dog = getDog() ...

Connecting your MongoDB database to your React.js frontend: A step-by-step guide

I have successfully set up my backend using express and MongoDB, which contains multiple collections. Now, I am looking to connect this MongoDB database to my react.js frontend in order to iterate through the data and display the collection names on the u ...

Unable to remotely access the 'three.js' library

After including a path to the online three.js library in my <script> tag within the index.html file, I am facing an issue where there is no access to the three.js library resulting in my script not working properly. <script src="https://three ...

I am curious to know how I can utilize Node.js to sum up values from a specific column within a CSV file

I recently started working with node.js and I'm currently working on a side project that I'm having some trouble with. My goal is to extract values from a specific column in an unzipped csv file and then add them up using node.js. Below is my co ...

Upon refreshing the Angular application in the browser, we received a response from Django

I am currently developing an application with a Django backend and an Angular frontend. Everything was working smoothly until I encountered an issue after refreshing a page in the browser. The Angular response stopped coming through, but I continued to rec ...

Exploring the syntax for navigating with JS Angular and HTML, such as when using the code snippet: ng-click="save(userForm)"

I am struggling to grasp the functionality of a specific part of this code. Despite my efforts to find tutorials, I have been unable to locate relevant information. There are two lines in particular that puzzle me: <button type="submit" class="btn btn ...

What is the process for altering the color of a radio button with Angular?

I'm a beginner in Angular and I'm trying to change the color of a radio button when it's selected and also retrieve its value. However, I've encountered an issue as I keep getting $scope is undefined. Below is the code snippet from my H ...

"Enhance Your Text Fields with Angular2 Text Masks for Added Text Formatting

Is there a way to combine text and numbers in my mask? This is what I am currently using: [/\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/] The above code only allows for numbers. How can I modify it to allow f ...

Standard layout for a project with equally important server and client components

We are in the process of developing an open-source library that will consist of a server-side component written in C# for Web API, meta-data extraction, DB operations, etc., and a client-side component written in TypeScript for UI development. Typically, ...

Implementing a Vue.js Scrollable Table

I am currently working on a table that is populated using the vue.js v-for method: <table> <tr><th>Name</th><th>Surname</th></tr> <tr v-for="user in users"><td>@{{user.name}}</td><td>@{ ...

Add the value of the td tag to an array when it is selected

I need to store the data from a table into an array, but only if the checkbox next to it is checked. Here's the code snippet: <table class="table table-bordered table-striped table-condensed flip-content" style="margin-top: 10em;"> <thead cl ...