How can I determine the quantity of pairs in an array using JavaScript?

My current approach is not providing me with the desired result. I am facing an issue where pairs of 1 are being counted multiple times, which is incorrect. What I actually need is to count only the "perfect" pairs, such as the pair between 5 and 2 in this case. As of now, my solution is returning 4 when it should be 2.

I am struggling to find a way to achieve this. Any suggestions would be greatly appreciated.

let ar1 = [12, 5, 5, 2, 1, 1, 1, 1, 2];

const countPairs = (ar) => {
  let obj = {};

  ar.forEach((item) => {
    obj[item] = obj[item] ? obj[item] + 1 : 1;
  });

  return Object.values(obj).reduce((acc, curr) => {
    acc += Math.floor(curr / 2);
    return acc;
  }, 0);
};

console.log( countPairs(ar1) )

Answer №1

To find the number of pairs in a list, you can filter the object values by 2 and then count them

let numbers = [12, 5, 5, 2, 1, 1, 1, 1, 2];

const countPairs = (arr) => {
  let obj = {};

  arr.forEach((num) => {
    obj[num] = obj[num] ? obj[num] + 1 : 1;
  });
  
  return Object.values(obj).filter(e => e == 2).length;
};

console.log(countPairs(numbers))

Answer №2

Here's a concise way to count pairs in an array using the Map method:

const countPairs = (arr) => [...arr.reduce((dict, n) => dict.set(n, (dict.get(n) ?? 0) + 1), new Map()).values(),].filter((n) => n === 2).length;

let exampleArray = [12, 5, 5, 2, 1, 1, 1, 1, 2];

const countPairs = (arr) =>
  [
    ...arr
      .reduce((dict, n) => dict.set(n, (dict.get(n) ?? 0) + 1), new Map())
      .values(),
  ].filter((n) => n === 2).length;

console.log(countPairs(exampleArray));

Answer №3

or that

const 
  ar1 = [12, 5, 5, 2, 1, 1, 1, 1, 2]
, countPerfectPairs = arr => arr.reduce((r,val,i,{[i+1]:next})=>
    {
    if(!r.counts[val])
      { 
      r.counts[val] = arr.filter(x=>x===val).length
      if (r.counts[val]===2) r.pairs++
      }
    return  next ? r : r.pairs
    },{counts:{},pairs:0}) 


console.log( countPerfectPairs(ar1) )

If you prefer Details:

const 
  ar1 = [12, 5, 5, 2, 1, 1, 1, 1, 2]
, countPerfectPairs = arr => arr.reduce((r,val)=>
    {
    if(!r.counts[val])
      { 
      r.counts[val] = arr.filter(x=>x===val).length
      if (r.counts[val]===2) r.pairs++
      }
    return r
    },{counts:{},pairs:0}) 


console.log( countPerfectPairs(ar1) )

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

Module-alias cannot be resolved by esm

Currently, I am utilizing the combination of esm package and module-alias. However, it appears that esm is not recognizing module-alias's paths. This is how I am loading my server file: nodemon -r esm ./src/index.js 8081 At the beginning of my inde ...

Is there a way for me to activate onMouseEnter on elements that are positioned behind other elements

I'm attempting to activate the mouseEnter event when the mouse is over multiple elements simultaneously. The goal is for both mouseEnter events to be triggered when the mouse reaches the center, and ideally for both elements to change to a yellow col ...

Locate a Checkbox using JQuery and NodeJS

Searching for the presence of a checkbox in a webpage using NodeJS with JQuery (other suggestions are welcome). However, I am struggling to locate the checkboxes within the form. Below is the code snippet from the webpage: <form id="roombookingform" c ...

What is the best way to create a linear flow when chaining promises?

I am facing an issue with my flow, where I am utilizing promises to handle the process. Here is the scenario: The User clicks a button to retrieve their current position using Ionic geolocation, which returns the latitude and longitude. Next, I aim to dec ...

Leveraging the push method within AngularJS

Hello, I am currently working on setting up an eCommerce shop using Angular. Below is the code snippet I am using: var shopApp = angular.module('shopApp', ["slugifier"], function() {}); controllers.productController = function($scope,FetchFa ...

Exception encountered with HTML5 cache manifest

I attempted to implement the application cache feature on my website, but I am facing a major issue. I only want to cache three specific files: style.css, favicon.ico, and script.js. The problem arises when the browser also caches other files such as inde ...

Storing customer information securely on the server with the help of Node.js

After spending some time experimenting with Node.js on my local machine, I've realized that my understanding of HTTP requests and XHR objects is quite limited. One particular challenge I've encountered while using Node is figuring out how to effe ...

combine a pair of elements simultaneously

I recently developed a nested directive for a multitabbed form, and here is a simplified version: <outer> <inner heading="a" src="'a.html'" active="true"></inner> <inner heading="b" src="'b.html'"></inner ...

unable to disable custom field component in Angular Material

I've built a unique slide toggle feature using Angular Material. The steps I followed to create it can be found here: https://material.angular.io/guide/creating-a-custom-form-field-control While everything works smoothly, there's an issue when I ...

The function you are trying to call is not valid... the specified type does not have any call signatures [ts 2349

Having some trouble using functions from Observable Plot example with a marimekko chart in my TypeScript project. I encountered an error on this particular line: setXz(I.map((i) => sum.get(X[i]))) The code snippet causing the issue is as follows: fu ...

Node.js request body is not returning any data

UPDATE: @LawrenceCherone was able to solve the issue, it's (req, res, next) not (err, res, req) I'm in the process of building a MERN app (Mongo, Express, React, Node). I have some routes that are functioning well and fetching data from MongoDB. ...

What sets Java classes apart from JavaScript classes?

After working with C# and Java, I decided to dive into learning javascript/node.js. However, I am facing some challenges trying to understand what is wrong with this code. Here is the snippet from my main.js file: const MyClass = require("./MyClass"); le ...

Tips for positioning dynamic high charts in a bootstrap row

I have implemented HighCharts for displaying charts on my website. Specifically, I am utilizing the chart type solidgauge. The charts are dynamic and I am looking to arrange them horizontally across the page. My goal is to align the charts in a layout sim ...

Issues with nested array filtering in JS/Angular causing unexpected outcomes

I am faced with a particular scenario where I need to make three HTTP requests to a REST API. Once the data is loaded, I have to perform post-processing on the client side. Here's what I have: An array of "brands" An array of "materials" An array o ...

Run a Python script to capture mouse coordinates using Selenium

Greetings, I am currently utilizing selenium webdriver to retrieve the X,Y coordinates of the cursor at a specific moment on the webdriver screen. However, I am facing challenges with the implementation of a method that involves using driver.execute_script ...

Guide to making Bootstrap collapsible panels with full-width content that do not affect neighboring columns

I'm currently working on a responsive grid that displays items with expandable details when clicked. My issue is that when one item expands, the elements next to it collapse down, which is not what I want. I want all items to stay at the top and have ...

Storing Data Property Value from an Item in Rendered List Using Vue: A Quick Guide

I'm currently working on implementing a follow button for list items in Vue. My approach involves extracting the value of a specific property from a list item and storing it in the data object. Then, I plan to utilize this value within a method to app ...

Implement a one-second delay before nesting another animation

I'm currently utilizing a timeout function, but I am interested in using a delay instead. My goal is to have the second animation start when one second has passed from the beginning of the first animation, and it should be a linear animation. How can ...

The issue of Access-Control-Allow-Origin not functioning properly when using Ajax for a POST request

I am encountering an issue with the header "Access-control-allow-origin" when making a request using the following code: <script type='text/javascript'> function save() { $.ajax( { type: 'POST', ur ...

Personalizing MaterialUI's autocomplete functionality

Trying to implement the material-UI Autocomplete component in my react app and looking for a way to display a div when hovering over an option from the list, similar to what is shown in this reference image. View example If anyone has any tips or suggest ...