Obtain a listing of values that appear multiple times within an array

I need a solution to find values that appear more than once in an array. The current code I have is quite complex.

var arr = [1, 2, 3, 4, 2, 3];
var flag = {}
var exist2arr = [];

for(var i = 0; i < arr.length; i++){
  for(var j = 0 ; j < arr.length; j ++){
     if(i !=j && arr[i] == arr[j]){
       if(!flag[arr[i]])
         exist2arr.push(arr[i]);
       flag[arr[i]] = 1;
     }
  }
}
console.log(exist2arr);

Is there a simpler way (using a built-in JavaScript function) to achieve this? Any suggestions would be greatly appreciated.

Answer №1

To eliminate duplicate values in an array, you can filter the array to include only values where the first occurrence is not at the current index. Then, you can convert the filtered array into a Set to get unique values.

const arr = [1, 2, 3, 4, 2, 3, 2, 3, 2, 3, 2, 3]; // added in some extras

const filtered = arr.filter((v, i) => arr.indexOf(v) !== i)
const unique = new Set(filtered)

console.info(Array.from(unique)) // using Array.from so it can be logged

Answer №2

let numbers = [1, 2, 3, 4, 2, 3];

let obj = numbers.reduce((obj, num) => {
  num in obj ? obj[num] += 1 : obj[num] = 1;
  return obj;
}, {});

let result = Object.keys(obj).filter(key => obj[key] > 1);

console.log(result);

Answer №3

This solution might be considered a bit unconventional, but it gets the job done efficiently and in linear time complexity:

var arr = [1, 2, 3, 4, 2, 3, 2, 2]

var a = arr.reduce((r, v) => ((r[v + .1] = r[v + .1] + 1 || 1) - 2 || r.push(v), r), [])

console.log( a )              // [2,3]
console.log({ ...a })         // to display the "hidden" items
console.log({ ...a.slice() }) // using .slice() to eliminate the excess items

Answer №4

One possible solution is as follows:

function countOccurrences(value, array) {
  var count = 0;
  for(var i = 0; i < array.length; i++){
    if(array[i] === value){
      count++;
    }
  }
  return count;
}
function findDuplicates(dupArray, num) {
  var minOccurrences = num === undefined ? 2 : num;
  var result = [];
  for(var i = 0, currentElement, length = dupArray.length; i < length; i++){
    currentElement = dupArray[i];
    if(!countOccurrences(currentElement, result) && countOccurrences(currentElement, dupArray) >= minOccurrences){
      result.push(currentElement);
    }
  }
  return result;
}
var testArray = [4, 5, 2, 5, 7, 7, 2, 1, 3, 7, 7, 7, 25, 77, 4, 2];
console.log(findDuplicates(testArray)); console.log(findDuplicates(testArray, 3));

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

Tips for Customizing the Appearance of Material UI Select Popups

My React select component is functioning properly, but I am struggling to apply different background colors and fonts to the select options. https://i.stack.imgur.com/kAJDe.png Select Code <TextField fullWidth select size="small" nam ...

Retrieving a JSON element using its name within a subquery in a Node.js MySQL environment

I've been working on a project that involves NodeJS and Mysql for the backend. Everything was going smoothly until I encountered a small issue after adding a SUBQUERY. Below is the Mysql Query: var GetHistoryPayments = function(code){ var qu ...

Using Vue.js to iterate through a nested array from an object key

This is a complex v-for loop nested inside another v-for. It displays a list of questions along with the corresponding answers for each question. The key for the question will be used as the key for grouped_answers. The structure of the v-for loop is show ...

Communication between different windows using Chrome

I am facing an issue with my HTML5 Framework where the debugger is not visible in fullscreen mode due to the canvas taking up the entire screen. I need a solution where the debugger can be opened in another tab or popup so it can be moved off to another mo ...

Manipulating an SVG file with JavaScript

Within the HTML code, there is a photo already added as an SVG file. I am interested in learning how to enable the user to select between two options - either a cross or a zero. Upon clicking on the designated area, the chosen figure should appear (resembl ...

Finding the correlation between SVG element IDs and JSON keysUnderstanding how to pair up

Currently, I have an SVG file that can be viewed here. My goal is to present specific data when elements within the SVG are clicked. The data is in JSON format and I am looking to match each ID of an SVG element with a key in the JSON data. If both the key ...

Problem identified with Vue.js: The Log in screen briefly flashes before redirecting the authenticated user (resulting in a full page refresh)

My routing is functioning properly, utilizing navigation guards to prevent users from accessing the login or register routes once they are signed in. However, when I manually type '/auth/signin' in the address bar, the login screen briefly appear ...

Disabling keypress function in onKeyPress, yet onChange event still activates

In my ReactJS component, I have implemented a function that is triggered by the onKeyPress event: onKeyPress(e) { if (!isNumeric(e.key) && e.key !== '.') { return false; } } Although this function successfully prevents non-numer ...

Polymer element created specifically for this project can be seen in the DOM, yet it does not display any content within the

Snippet: <link rel="import" href="../../../../bower_components/polymer/polymer.html"> <link rel="import" href="../../../../bower_components/app-layout/app-drawer-layout/app-drawer-layout.html"> <dom-module id="app-index"> <templa ...

Adjusting ES2015 Map to accommodate the expected functionality

Exploring the capabilities of ES2015 Maps has been quite exciting, as I'm starting to see its potential. However, I've encountered a use case that has me stumped on whether Maps can handle it. Let's take a look at my class: class A { ...

Is there a built-in constant in the Angular framework that automatically resolves a promise as soon as it

I'm facing a situation where I have code that checks a conditional statement to decide if an asynchronous call should be made. If the condition is not met, the call is skipped. However, I still need to perform some final action regardless of whether t ...

How can I extract the return value of a JSON object and store it in a variable?

I am attempting to develop a dynamic chart by utilizing data retrieved from a function housed inside a JSON object. The JSON object is fetched through the Relayr Javascript API, and looks like this: relayr.devices().getDeviceData({ token: tok ...

JavaScript equivalent code to C#'s File.ReadLines(filepath) would be reading a file line

Currently in my coding project using C#, I have incorporated the .NET package File.ReadLines(). Is there a way to replicate this functionality in JavaScript? var csvArray = File.ReadLines(filePath).Select(x => x.Split(',')).ToArray(); I am a ...

Tips for choosing a single checkbox from a set of multiple checkboxes in React.js

I iterated through a list of objects to generate table rows, each containing an input tag with the type set as checkbox. const [ isChecked, setIsChecked ] = useState(false); const handleChange = (e) => { setIsChecked(e.target.checked) ...

Tips for deleting multiple objects from an array in angular version 13

I am facing an issue where I am trying to delete multiple objects from an array by selecting the checkbox on a table row. However, I am only able to delete one item at a time. How can I resolve this problem and successfully delete multiple selected objects ...

AngularJS Compile directive allows you to specify functions that you want to run in

Can someone assist me in understanding how to call an external function from a built-in compile directive? Here is a code example: http://plnkr.co/edit/bPDaxn3xleR8SmnEIrEf?p=preview This is the HTML: <!DOCTYPE html> <html ng-app="app"> ...

What is the best way to determine the highest and lowest values in a String[] array?

I stumbled upon the method to find the maximum and minimum values of an array on this website. It's effective, but I'm curious if there's a more efficient way to shorten the code. Perhaps there's a specific command that can simplify the ...

Am I on the right track with incorporating responsiveness in my React development practices?

Seeking advice on creating a responsive page with React components. I am currently using window.matchMedia to match media queries and re-rendering every time the window size is set or changes. function reportWindowSize() { let isPhone = window.matchMed ...

learning how to combine two json arrays of objects and showcase them in a react component

What is the best way to combine this data and present it in a table with a map using React? The text will be in the first column and the count in the second. const handleSubmit = async (event) => { event.preventDefault(); let URL1 = " ...

The dropdown menu component in ReactJS is malfunctioning

I'm currently working on a form that includes a select box which fetches data from the server and posts it back to the same server. I have implemented the select box component from ant design. Unfortunately, I've encountered an issue with the ha ...