Identify and remove numbers from an array that have the same digit, without having prior knowledge of which digit it

Is there an easy way to separate values in an array of random numbers between 0-99 based on their first and second digits? I need two arrays: one for values that share the same first digit, and another for values that share the same second digit. The actual digit value doesn't matter; as long as it is repeated within a number. Just to clarify, the digits 0-9 should be treated as if the first digit was 0.

For example, given the array:

[0, 10, 20, 11, 19, 12, 54, 64, 23, 24]
, the resulting arrays would be: [10, 11, 12, 19, 23, 24] and [0, 10, 20, 24, 54, 64]. Some values can appear in both arrays if they meet the specified criteria.

I have come across solutions that work when you know the specific digit you are looking for, but in this case, I am unsure how to proceed.

One suggested approach is to convert the numbers in the array into strings using array.map(String), so that the first and second digits can be accessed as first[0] and second[1]. However, I am unsure about the next steps. Any suggestions would be greatly appreciated.

Answer №1

To organize your array by grouping numbers based on their first and last digits, create an object accumulator. Then, sort the grouped array based on their length.

const input = [0, 10, 20, 11, 19, 12, 54, 64, 23, 24],
      groupLastDigits = input.reduce((result, num) => {
        const lastDigit = num % 10;
        result[lastDigit] ??= [];
        result[lastDigit].push(num);
        return result;
      }, {}),
      groupFirstDigits = input.reduce((result, num) => {
        let firstDigit = Math.floor(num / 10);
        if(firstDigit === num) firstDigit = 0;
        result[firstDigit] ??= [];
        result[firstDigit].push(num);
        return result;
      }, {}),
      extractNumbers = obj => Object.values(obj).filter(arr => arr.length > 1).flat(),
      commonLastDigits = extractNumbers(groupLastDigits),
      commonFirstDigits = extractNumbers(groupFirstDigits);
console.log(commonLastDigits);
console.log(commonFirstDigits);

Answer №2

Presenting a versatile solution for dealing with n digits!

function* identifyMatchingDigitClusters(inputArray) {
  
  // Keep in mind that very large numbers may be converted to strings
  // in scientific notation, potentially affecting the approach
  let maxDigits = Math.max(...inputArray.map(number => `${number}`.length));
  let stringsArr = inputArray.map(number => {
    let str = `${number}`;
    while (str.length < maxDigits) str = `0${str}`;
    return str;
  });
  
  for (let i = 0; i < maxDigits; i++) {
    
    let result = [];
    for (let n = 0; n <= 9; n++) {
      let matchingDigits = stringsArr.filter(str => str[i] === `${n}`);
      if (matchingDigits.length > 1) result.push(...matchingDigits);
    }
    yield result;
    
  }
  
};

let testCases = [
  [ 0, 10, 20, 11, 19, 12, 54, 64, 23, 24 ],
  [ 100, 200, 300 ],
  [ 111, 222, 333, 771, 828, 399 ],
  [],
  [ 1 ],
  [ 92929, 91919 ]
];
for (let inputArr of testCases) {
  console.log(`Digit Clusters for: [ ${inputArr.join(', ')} ]`);
  for (let cluster of identifyMatchingDigitClusters(inputArr)) console.log(`  [ ${cluster.join(', ')} ]`);
}

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

Problem encountered while processing JSON decode array: invalid string index

Whenever I try to use json_decode on an API response, the output I get is as follows: Array ( [Description] => { "CustomerData": [ { "CustomerId": "XXXXX290", "MemExpiryDate": "2301", "MobileNo": "XXXXXXX833", ...

JavaScript WYSIWYG Algorithm

Despite my searches on SO, it appears that most questions revolve around simply making a div editable using contenteditable="true". I am interested in finding the most effective method for tracking all formatting tags applied to a document. Merely togglin ...

What is a sophisticated method to hide an element from view?

My dilemma involves a dropdown menu and a list of elements that are initially set to hidden using CSS. When an item is selected from the dropdown, it becomes visible. However, I am struggling with finding a way to revert the previously selected element b ...

Customized content is delivered to every client in real-time through Meteor

I am currently working on creating a multiplayer snake game using three.js and meteor. So far, it allows one player to control one out of the three snakes available. However, there is an issue where players cannot see each other's movements on their s ...

Guide to iterating through several categories within a single row with PHP and MySQL

In my database, I have a table named 'category' with the following structure: parent_cat cat_id title 0 1 fruit 0 2 vehicle 0 3 goods 1 4 sour 1 ...

What are the steps involved in manipulating objects within an asynchronous result object?

I'm interested in learning how to manipulate a JS object from one file into another asynchronously, as my experience with asynchronous code principles is limited. Scenario: In my app.js file, I dynamically generate 'app panels' based on ...

Tips on integrating Codrops tutorial codes into a SilverStripe website project

Exploring the vast array of tutorials and code examples on the Codrops site has been an enlightening experience. Codrops Website I'm eager to incorporate some of these resources into my SilverStripe projects as well. SilverStripe CMS After learning h ...

Nest an array inside another array using a foreach loop

I've successfully created a code that generates two arrays using foreach loop and existing data. Now, I am looking to merge these two arrays into one. Below is the code for the first array : $sql = "SELECT photoprofile,username from photo WHERE usern ...

When rendering inside *.map in React, the first object of the array may not be rendered

When the SearchCard component is being rendered, it seems to be skipping the first object in the array- const cardArrayTrackSearch = this.state.searchtrack.map((user, i) => { return ( <SearchCard key={i} reload={th ...

What is the method to assign multiple values to ng-disabled in AngularJS?

Is there a way to assign multiple values for ng-disabled in AngularJS? The issue I'm facing is demonstrated in the following JS Fiddle: http://jsfiddle.net/FJf4v/10/ <div ng-app> <div ng-controller="myCnt"> <h3>A ->> ...

Wildcard GET requests in Express cause routing issues when navigating to a React application

My project is derived from the React-Webpack boilerplate repository found at this link: (https://github.com/wallacyyy/webpack-heroku/blob/master/server.js). Initially, everything was working fine but now I want to add routing within my React application. T ...

Showing an individual image when a particular list item is clicked using jquery

I have created an image slider that automatically transitions between images. However, I would like to have a specific image displayed when a particular list item is clicked in the round buttons below. For example, if the slider is showing the 5th image a ...

Using Javascript to transmit audio via a microphone

I am currently trying to use Selenium to simulate a user on a website that features audio chat. My goal is to emulate the user speaking through the microphone. While I have come across several resources discussing how to listen to the microphone in JavaSc ...

What is the method to exhibit the outcome of a promise on a web page within a React component?

In my search for information about promises, I have noticed that most articles provide examples using console.log. However, I am faced with a different scenario. I am working with AWS Athena and I need to display the result on a webpage in my React export. ...

Refresh the html page periodically by utilizing ajax every X seconds

Recently, I came across a post discussing the topic of automatically refreshing an HTML table every few seconds. The post can be found here. Currently, I am working with Rails and I want to achieve a similar functionality. However, I specifically want to ...

"Explore the versatility of React Day Picker with customizable months and weekdays_long

I have implemented the following packages: "react": "^18.2.0", "react-day-picker": "^8.1.0", and I am attempting to translate the months and days into French. However, despite passing the translated arrays to my < ...

The attempt to load a JavaScript resource has resulted in an error: the file was not located, despite the fact that it is a

Recently, I came across a new challenge in my application. Whenever I navigate to specific pages, I notice an error message in the development console: inject.preload.js:373 GET blob:http://my-app-name.test/ba65127c-383e-45b7-8159-9b52ea288658 0 () Upon ...

The scatterplot dots in d3 do not appear to be displaying

My experience with d3 is limited, and I mostly work with Javascript and jQuery sporadically. I am attempting to build a basic scatterplot with a slider in d3 using jQuery. The goal of the slider is to choose the dataset for plotting. I have a JSON object ...

Allowing the primary content to span the entire width of the mobile screen

I have scoured various forums in search of answers, but unfortunately, I haven't found a solution that fits my specific query. I am looking to ensure that the .main-content (article text and images) occupies the full width of the mobile screen without ...

Using Phonegap alongside ons-scroller and ons-button

Recently, I have been using Phonegap with the Onsen UI system on iOS devices. I encountered an issue where buttons included within an ons-scroller were not clickable when running on an iPad or iPhone. Here is the code snippet that caused the problem: < ...