moving all duplicate elements in an array into a separate array

I am struggling to achieve the result [1,1,1,1,2,2,20,20] from the given array.

My goal is to extract all duplicate values into a new array, but I just can't seem to get it right. Can you please assist me?

const array = [1, 2, 4, 591, 392, 391, 2, 5, 10, 2, 1, 1, 1, 20, 20];

const dupArray = (arr) => {
  let newArray = array.sort();
  let filteredArray = [];
  for (y = 0; y < newArray.length; y++) {
    for (i = y + 1; i < newArray.length; i++) {
      if (newArray[y] === newArray[i]) {
        filteredArray.push(newArray[i]);
      }
    }
  }

  return filteredArray
};

console.log(dupArray());

Answer №1

I believe the anticipated outcome will be: [1, 1, 1, 1, 2, 2, 2, 20, 20]

Snippet:

const array = [1, 2, 4, 591, 392, 391, 2, 5, 10, 2, 1, 1, 1, 20, 20]

const dupArray = (arr) => Object
  .entries(arr.reduce((a, c) => (a[c] = ++a[c] || 1, a), {}))
  .filter(e => e[1] > 1)
  .map(e => Array(e[1]).fill(+e[0]))
  .flat(1)

console.log(dupArray(array))

Answer №2

Providing you with the duplicates array to assist you.

const findDuplicates = (inputArray) => {
  let sortedArray = inputArray.slice().sort(); 
  let duplicateValues = [];
  for (let i = 0; i < sortedArray.length - 1; i++) {
    if (sortedArray[i + 1] == sortedArray[i]) {
      duplicateValues.push(sortedArray[i]);
    }
  }
  return duplicateValues;
}

let originalArray = [1, 2, 4, 591, 392, 391, 2, 5, 10, 2, 1, 1, 1, 20, 20];
alert(`Original Array: ${originalArray}, Duplicates: ${findDuplicates(originalArray)}`);

Answer №3

If you're looking to identify duplicates in an array, a simple filter function can do the trick.

const array = [1, 2, 4, 591, 392, 391, 2, 5, 10, 2, 1, 1, 1, 20, 20];

const findDuplicates = (arr) => arr.filter( x => 
  arr.filter(y => y === x).length > 1
).sort()

console.log(findDuplicates(array))

The logic behind this code is as follows:

  1. Iterate through the elements of the array and filter out elements that have more than one occurrence
  2. Sort the resulting array to display duplicate elements in ascending order

Answer №4

Presented below are two efficient approaches for sorted arrays. In my analysis, the expected result should be [1,1,1,1,2,2,2,20,20]

const array = [1, 2, 4, 591, 392, 391, 2, 5, 10, 2, 1, 1, 1, 20, 20];

//Implementing the first solution
const dupArray = (arr) => {
  arr = arr.sort((a,b) => a-b);
  let filteredArray = [];
  let currentElement = null;
  for(let i = 0; i < arr.length; i ++){
    if(arr[i] === currentElement){
      filteredArray.push(arr[i]);
    }else{
      currentElement = arr[i];
      if(arr[i] === arr[i+1]){
        filteredArray.push(arr[i]);
      }
    }
  }
  return filteredArray;
};

//Introducing the second solution
const dupArray2 = (arr) => {
  arr = arr.sort((a,b) => a-b);
  for(let i = 0; i < arr.length; i ++){
    if(arr[i] != arr[i-1] && arr[i] != arr[i+1]){
      arr.splice(i,1);
      i -= 1;
    }
  }
  return arr;
};
console.log(dupArray(array));
console.log(dupArray2(array));

Answer №5

Initially, I implemented a custom sorting function within array.sort() to achieve an ascending order. I introduced a boolean flag called hasDuplicates to track if duplicates have been encountered previously. If not, the element is duplicated and added to the array. To prevent re-processing of elements, I assigned y as i-1.

From an efficiency standpoint, this approach efficiently linearly traverses the array only once.

const array = [1, 2, 4, 591, 392, 391, 2, 5, 10, 2, 1, 1, 1, 20, 20];

const dupArray = (arr) => {
  let newArray = array.sort((a, b) => a - b);  
  let filteredArray = [];
  for (y = 0; y < newArray.length; y++) {
    let hasDuplicates = false;                
    for (i = y + 1; i < newArray.length; i++) {
      if (newArray[y] === newArray[i]) {    
        filteredArray.push(newArray[i]); 
        if(!hasDuplicates) {               
          filteredArray.push(newArray[i]);
          hasDuplicates = true;
        }
      } else {
        y = i - 1;
        break;
      }
    }
  }

  return filteredArray
};

console.log(dupArray());

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

Adding functions to the prototype of a function in JavaScript

Is there a more concise way to simplify this code snippet? var controller = function(){ /*--- constructor ---*/ }; controller.prototype.function1 = function(){ //Prototype method1 } controller.prototype.function2 = function(){ //Prototyp ...

Styling Javascript Objects

[ [ {"path":"path2","value":"kkk"}, {"path":"path0","value":"uuu"}, {"path":"path1","value":"ppp"} ] ] The result obtained from my manipulation is shown above. However, I require the format to be as depicted below: ["path":"pat ...

I attempted to publish my React application using gh-pages and encountered the following error: "The argument for 'file' must be a string. However, it was received as undefined."

I encountered an issue while attempting to deploy my React application with gh-pages. The error message I'm facing states: "The 'file' argument must be of type string. Received type undefined." Initially, I suspected that the problem was wi ...

Utilize Object literal manipulation to include properties in a specific sequence

Working on a tool to generate Nassi-Shneiderman diagrams online, where each diagram is represented as an object literal with unlimited possible children. As I aim to add a sequence into the while loop following the first sequence, I encounter the challeng ...

At times, Vue.js may encounter difficulties when attempting to load a component

Recently, a strange issue has been occurring in my production code. Although nothing has been changed, I am now receiving reports that occasionally a template fails to load causing the page to crash. I am currently using vue 2.16. The error messages being ...

Encountering an issue in Typescript where utilizing ref in ShaderMaterial triggers an error stating: "The anticipated type is originating from the property 'ref' declared within the 'PolygonMat' type definition."

While working on a shaderMaterial with the drei library, I encountered an issue with TypeScript when using ref: Type 'RefObject<PolygonMat>' is not assignable to type 'Ref<ShaderMaterial> | undefined'. I defined the type ...

Unable to retrieve values from JSON objects within an array

My array consists of multiple objects, each containing specific properties such as: [ { "id":17368, "creationDate":1566802693000, "status":"InProgress", "type":"NEW", "agentType":"Master" }, { "id":17368, ...

Instead of storing the result in a variable, return the value directly in Angular2

This particular code snippet is designed to load a JSON file asynchronously and place the result into the variable _values. private getValue(name) { this.http.get('http://localhost:8080/getValue/' + name) .subscribe(res => this._values = re ...

In certain Express app files, the use of Sequelize modules may result in a return value of undefined

Objective - To implement a middleware-like callback in userHandler located in util.js for certain express routes in an express app, created using express-generator and sequelize-cli. Expected Outcome - Utilize the user model successfully in routes and use ...

Is there a way for me to determine the quality of a video and learn how to adjust it?

(function(){ var url = "http://dash.edgesuite.net/envivio/Envivio-dash2/manifest.mpd"; var player = dashjs.MediaPlayer().create(); player.initialize(document.querySelector("#videoPlayer"), url, })(); var bitrates = player.getBitrateInfoListFor("vid ...

Encountering 'Unacceptable' error message when attempting to retrieve response via AJAX in the SPRING

I'm encountering an issue with my code where I am trying to retrieve a JSON array response from a controller class. Whenever I send a request from JavaScript, I receive a "Not Acceptable" error. Can someone please assist me in identifying the bug in m ...

What is the best way to optimize performance by transferring data efficiently from a database?

Seeking assistance with javascript. I have a database table that indicates which web elements to display based on a numeric key property. There are 4 boolean values associated with each key. Currently, I make an ajax postback to the server, but I am looki ...

Get a Google Sheets file in CSV format

Currently, I am in the process of developing cloud functions for pushing data to Google AutoML. I have successfully created a function to generate the necessary data. However, for the next phase, I am curious about the possibility of downloading a Google ...

Data entry and a dropdown menu

Looking to add a dynamic numeric input that changes based on a select box choice. The numeric input will have a specific range based on the selected option from the select box. For instance: If option2 is selected, the numeric input range will be from 2 ...

Select a user at random from the reactions in the message

Is there a way to select a user at random from message reactions on Discord? Despite going through all the documentation, I'm still unsure about how to do this. ...

Is it possible to filter a single field for two different values in a relationMapping using Objection.js?

In an Objection.js model, I have a relation mapping where I need to set a filter on a field that can only have two possible values: null or 0. Here is an example of the relation I am using: static get relationMappings() { return { dipendenti: { ...

Combining Express.js-REST-Endpoint with a Meteor Application

I'm facing a bit of a challenge here: I am currently in the process of developing a feature-rich application using Meteor. However, I also need to provide some functionality as a REST-Service for automation purposes (another application should be able ...

Encountering an Assertion Error when attempting to import a custom package in Angular 13

Seeking assistance: I have developed my initial Angular package which offers various services for making HTTP requests to a server and fetching results. Upon importing the service, the webpage ceases to render and displays the following error message: cor ...

Security ExpoStore malfunctioning (React Native, TypeScript)

I am currently developing a mobile phone application that utilizes Stripe and Expo Bar Code Scanner. Upon launching the application, if camera permissions are granted, users can scan bar codes which contain only the id of the scanned item. If the item exis ...

In JavaScript, using square brackets before a method allows for dynamic method

Does anyone know the significance of the square brackets preceding the method call in this code snippet? It's a new syntax for me... return [].concat(privateUserList); Appreciate any insights! ...