JavaScript - Modifying repeating numbers in an array

I have a list of numbers that repeats multiple times like this;

numbers = [2,3,1,2,1,3,3,1,2]

My goal is to increase each repeated number by 10 every time it appears. Therefore, the updated list should look like this;

updated_numbers = [2,3,1,12,11,13,23,21,22]

It's important to note that the order of the numbers in the list must stay the same.

This example only shows a small portion of the actual list, which contains repetitive sequences of numbers.

If you have any suggestions on how to achieve this task efficiently, I would greatly appreciate it.

Answer №1

To calculate the final results, simply create a lookup table that counts the frequency of each number in the list. Then, multiply the frequency by 10 and add it to the original number.

const numbers = [4,7,2,8,2,7,7,2,4],
      countMap = {},
      finalResult = numbers.map(num => {
        countMap[num] = (countMap[num] || 0) + 1;
        return num + (countMap[num] - 1) * 10;
      });
console.log(finalResult);

Answer №2

One way to achieve this is by following these steps:


var numbers = [8,9,7,8,7,9,9,7,8];
var countMap = {};

numbers.forEach(function(num, idx) {
    if(countMap[num]) {
        numbers[idx] = num + (10 * countMap[num]);
        countMap[num] = countMap[num] + 1;
    } else {
        countMap[num] = 1;
    }
});

Answer №3

To create a more concise version, you can use a closure to keep track of counting by assigning zero to unknown properties and incrementing the value.

const
    list = [2, 3, 1, 2, 1, 3, 3, 1, 2],
    result = list.map((o => v => v + 10 * (o[v] ??= 0, o[v]++))({}));

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

"Enhance the visual appeal of your Vue.js application by incorporating a stylish background image

Currently, I am utilizing Vue.js in a component where I need to set a background-image and wrap all content within it. My progress so far is outlined below: <script> export default { name: "AppHero", data(){ return{ image: { bac ...

Filtering objects in AngularJS is a complex task, especially when you need to be able to search for a specific value but also consider if that value exists

Struggling to convey my thoughts in English, but here it goes. Imagine two objects linked by colorid: $scope.fruits = {{name:"apple",colorid:"1"},etc}; $scope.colors = {{id:"1",value:"red"}; I've created a table with search and filter function ...

Personalize Badge Component

I've been on the hunt for a solution to customize a badge component similar to what's seen here: https://mui.com/material-ui/react-badge/. As of now, only options for making it a dot or adding a number in a circle are available. However, I' ...

The function called Nuxt: n2 is not defined

When using Nuxt 3, I encountered a TypeError that looks like the following: Uncaught TypeError: n2 is not a function My issue revolves around a button that triggers the function toggleSelectRow with a @click.prevent directive. The function in question is ...

I encountered an issue with adding a console log in the getStaticProps() function that resulted in the error: SyntaxError: Invalid Unicode escape sequence at eval (<anonymous>

Welcome to my users.js page! import React from 'react' const displayUsers = ({users}) => { return ( <> { users.map(user => { return <div key={user.id}> {user.name} </div> }) } </&g ...

In JavaScript, loop through an array of arrays and combine them using the concat

If I have an array like [["a", "b"], ["c", "d"]], is there a way to iterate, reduce, map, or join this array in order to get the desired output of ["ac", "ad", "bc", "bd"]? What if the array is structured as [["a", "b"], ["c", "d"], ["e", "f"]]; how can we ...

Is it possible to utilize Webpack 5's ChunkGroup API with several entries?

I am encountering an error message when attempting to upgrade from Webpack 4 to Webpack 5. The error states: Module.entryModule: Multiple entry modules are not supported by the deprecated API (Use the new ChunkGroup API) I have searched for information o ...

Utilize the UseQuery graphql function in conjunction with the useState hook within useEffect, allowing for the execution of an additional useEffect to update additional state

In my NextJS project, I am utilizing Apollo for graphQL queries and encountering an issue with the stateData.allProducts section. Despite setting the state in the useEffect and including data as a dependency in the array, the error claims it is null when d ...

Transferring JSON data through AJAX to a PHP backend

I have been working on a solution to convert a CSV file into JSON and then send it to BigCommerce using their REST API. Initially, I planned to use Javascript for the entire process, and everything was successful until I encountered issues with CORS when t ...

Obtain the breakpoint value from Bootstrap 5

We have recently updated our project from Bootstrap 4 to Bootstrap 5. I am trying to retrieve the value of a breakpoint in my TypeScript/JavaScript code, which used to work in Bootstrap 4 with: window .getComputedStyle(document.documentElement) .g ...

Modifying a single element within a struct array will result in modifications being applied to all elements

My goal is to modify variables of structs within an array, but I've encountered an issue where changing one variable affects the others in the array as well. I've attempted using -> and (*logEntries[i]), but neither method seems to work as int ...

Testing the throwing of errors when running Karma by utilizing sinon.spy on global functions like parseInt

I'm currently facing an issue with monitoring the usage of parseInt within my function. This is a Proof of Concept for integrating TypeScript into our company's workflow. I've tried following two different tutorials on testing Sinon, but no ...

Retrieve all attributes of an element with the help of jQuery

I am attempting to extract all the attributes of an element and display their names and values. For instance, an img tag may have multiple unknown attributes that I need to access. My initial idea is as follows: $(this).attr().each(function(index, element ...

Unsuccessful translation of HTML symbol codes within a toggle function using jQuery

Is there a way to toggle between the symbols + and - using HTML entity codes &#43; and &#45;? I have attempted different solutions for toggling HTML content, but none seem to work correctly with these specific codes. It toggles once, but doesn&apo ...

Error in React-router: Unable to assign value to the 'props' property as it is undefined

Currently, I am working on setting up routing with Meteor using the react-router package. However, I have encountered a specific TypeError: Here is a link to an image that provides more context: This is the code snippet from my main.js file: import Reac ...

Guide on exporting type definitions and utilizing them with npm link for a local package

I am in the process of developing a new testing tool called tepper as an alternative to supertest. My goal is to make this package available in both ESM and CJS formats. However, I'm encountering an issue where users of the library are unable to locat ...

Array failing to populate with accurate information

During the loop, I am populating an array: for k in one two three; do array+=( "$k" ) done echo $k[0] # Expecting to print 'one', but prints 'one[0]' echo $k[1] # Expecting to print 'two', but prints 'one[1]' W ...

Transform JSON String into Object using jQuery

Recently, I came across a JSON String in this format. {"label":"label","label1":"67041","label2":"745","label3":"45191","label4":"11‌​464"} I needed to convert it into an object structure like this [{"label":"label","label1":"67041","label2":"745"," ...

Discovering the specific DOM element that has been clicked using only JavaScript

Looking to enhance my HTML document with interactivity, I wanted to achieve a feature where clicking on a div element would display its respective id. I attempted the following approach: window.onload = function() { associateIds(); clicked(); } fu ...

Ways to obtain data in JavaScript function from HTML

Struggling to pass the key from a database query in HTML using PHP to a JavaScript function? You're not alone. The challenge lies in passing the field_id to the updateRecords() JS function through the onClick() event of an HTML button. Previously, se ...