Analyzing objects within an array for similarities

Suppose I have an array containing objects:

 var arr = [ 
   { id: 1, pt: 0 },
   { id: 2, pt: 12 },
   { id: 3, pt: 7 },
   { id: 4, pt: 45 },
   { id: 5, pt: 123 },
 ];

I am looking to loop through this array (possibly using array.forEach or array.map) and compare the pt attribute of each item with that of the other items in the array. My goal is to identify the three other items with values closest to the current item's pt value. For instance, for id: 1, the closest items in value would be 2, 3, and 4. Similarly, for id: 3, it would be 1, 2, and 4, and so on. How can I achieve this?

Answer №1

In order to obtain the desired outcome, one could apply a filtering mechanism to remove the pivot element and then arrange the data based on absolute difference, ultimately selecting the specified number of items as output.

function closest(n, { id, pt }) {
    return array
        .filter(o => o.id !== id)
        .sort((a, b) => Math.abs(a.pt - pt) - Math.abs(b.pt - pt))
        .slice(0, n);
}

var array = [{ id: 1, pt: 0 }, { id: 2, pt: 12 }, { id: 3, pt: 7 }, { id: 4, pt: 45 }, { id: 5, pt: 123 }],
    result = array.map(o => Object.assign({}, o, { closest: closest(3, o) }));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

Let's start by organizing the array:

array.sort((a, b) => a.pt - b.pt);

Next, the nearest elements can be found directly before or after the element. To locate them, simply move forward and backward:

function findNearest(position, count) {
  let lower = position - 1, upper = position + 1;
  const calculateDistance = index => Math.abs(array[position].pt - array[index].pt);
  const result = [];
  while(result.length < count) {
    if(lower >= 0 && calculateDistance(lower) < calculateDistance(upper)) {
       result.push(array[lower--]);
    } else if(upper < array.length) {
       result.push(array[upper++]);
    } else break;
  }
 return result;
}

To find the five closest ancestors of the first element:

findNearest(0, 5)

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

Python code to transform an integer array into a binary array

I'm attempting to convert an array of integers into binary format using Python 2.7. Here's a simplified version of the code I'm working with: #!/usr/bin/python import numpy as np a = np.array([6, 1, 5, 0, 2]) b = np.zeros((5)) for i i ...

Is it possible for me to use the name "Date" for my component and still be able to access the built-in "new Date()" functionality?

Currently following the NextJS tutorial, but adding my own twist. In the NextJS example, the custom component is named "Date" (/components/date.js) and does not utilize the built-in Date() object in processing, making it unique to the file. In my scenario ...

Search through an array of objects and assign a new value

I am facing a challenge with an array of objects structured as shown below: [ { "e_id": "1", "total": 0 }, { "e_id": "3", "total": 0 } ] My objecti ...

Is there a way to remove a row through fetch using onclick in reactjs?

I'm completely new to this and struggling with deleting a row using fetch. I've written some messy code and have no idea if it will even work. Please help, I feel so lost... renderItem(data, index) { return <tr key={index} > &l ...

Ways to retrieve a precise quantity of information from an associative array while setting a limit on a particular key's highest value

Let's say we have an array called $array1 which contains information about individuals including their age: $array1 = array( array('id'=>'a','age'=>21), array('id'=>'b','age&apos ...

How can I properly choose distinct values for an individual attribute from a JavaScript array containing objects?

Let's imagine a scenario with an array of JavaScript objects like this: var data = [ {category : "root", type: "qqqqq", value1: "aaaaa", value2: "zzzzz"}, {category : "root", type: "qqqqq", value1: "aaaaa", value2: "xxxxx"}, {category : " ...

What is the method with the greatest specificity for applying styles: CSS or JS?

When writing code like the example below: document.querySelector('input[type=text]').addEventListener('focus', function() { document.querySelector('#deletebutton').style.display = 'none' }) input[type=text]:focu ...

When using the test() method in JavaScript with regular expressions, it may return true even if not all characters match, even when using

When attempting input validation in a textarea, I encountered the following issue: const re= /^[0-9A-Za-zÀ-ÿ\s\’\'\:\.\-\,\!\[\]\(\)\@\&\?]+?$/im; re.test(control.valu ...

send array to the sort function

How can I sort a data array that is returned from a function, rather than using a predefined const like in the example below: const DEFAULT_COMPETITORS = [ 'Seamless/Grubhub', 'test']; DEFAULT_COMPETITORS.sort(function (a, b) { re ...

I'm facing an issue with converting my object to an array as I keep getting the message: "ERROR TypeError: undefined

ERROR TypeError: undefined is not a function Why am I unable to convert my object to an array? This error keeps popping up as I attempt to map all the items that are currently objects but need to be converted into arrays for mapping. How can I accomplish ...

Reactjs, encountering a hitch in utilizing material UI: Incompatible hook call detected

As a newcomer to React, I decided to incorporate Material UI components into my project. After installing the components locally using npm install and importing them into my project, I encountered an error when trying to run start: Error: Invalid hook call ...

Using Jquery .ajax to Populate Select Dropdown with JSON Data

I have put in a lot of effort but I'm not seeing any results. My JSON data, created with PHP, looks like this (with the header sent before the data): {"users":[ {"id":"3256","name":"Azad Kashmir"}, {"id":"3257","name":"Balochistan"}, {"id":"3258","na ...

Enhancing Image Upload with Ajax/JavaScript: Generating Multiple Previews

I've been experimenting with an Ajax image uploader that I found on this website. Currently, I have managed to create duplicate preview images: one displayed under the input field and the other elsewhere on the page labeled as "this what you chose". H ...

Display text on the screen with a customized design using JavaScript's CSS styles

I need help with printing a specific page that contains some information designed in print.css. I want to print this page, including an image, with the same style. function printContent() { var divContents = document.getElementById("terms").innerH ...

A Guide to Making a Floating Widget That Can Move Beyond the Boundaries of a Website in React

Currently, I am in the process of developing a project that requires the implementation of a floating widget capable of overlaying content not just within the confines of the website, but outside as well. This widget needs to have the ability to remain on ...

Hide the content within a table row by setting the display to

I need to hide the div with the id "NoveMeses" if all h3 elements display "N.A." Is there a way to achieve this? If both h3 elements in row1 and row2 contain the text "N.A.", I want the div NoveMeses to be hidden. Below is the code snippet using AngularJ ...

The attribute 'inventory' cannot be found in the declaration of 'WarehouseModule'

I am facing an issue with my AngularFire setup. I have recently installed the latest version of AngularFire using npm i @angular/fire and have successfully configured Firestore. However, when attempting to load data into my Firestore database, I encounte ...

What is the best way to create a JavaScript function that can be used for multiple expandable cards in HTML and CSS?

I'm dealing with a situation where I have a list of cards, and I want to be able to expand the content individually when clicking on "more info". Can someone offer advice on how to achieve this using Javascript? Check out this CodePen for reference: ...

Updating Kendo by modifying the Angular model

While working on a project with Angular, I recently discovered the Kendo-Angular project available at . I successfully integrated Angular-Kendo into my project and it seems to be functioning well, except for updating models in the way I am accustomed to. ...

What are the distinctions between altering the value of a textarea with JS and user input?

I've come across an interesting scenario that I'm hoping someone with more expertise in JavaScript can help me with. There is a popular online forum site that I frequently use. In the past, I was able to easily update a comment textarea using Jav ...