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

Using AJAX to retrieve a specific JSON object from an array of JSON data

Data retrieved in JSON array from the API: [{"id":"001", "name":"john", "age":"40"}, {"id":"002", "name":"jane", "age":"30"}] Using Ajax: $.ajax({ url: 'interface_API.php', ...

React error #425: Timezone formatting causing minification issue

Encountering a strange issue that seems to only occur on Vercel. The error message reads: Uncaught Error: Minified React error #425; visit https://reactjs.org/docs/error-decoder.html?invariant=425 for the full message or use the non-minified dev environme ...

What is the best way to send props from page.js to layout.js in the Next.js app directory?

Is there a way to effectively pass props to layouts in Next.js 13? Can we optimize the approach? Here's an example: // layout.js export default Layout({children}) { return ( <> {/* Display different `text` based on the page.js being ...

Create a lockscreen feature in AngularJS that becomes active after a period of inactivity

I am looking to integrate a lockscreen feature into my app using Angular.js. This lockscreen will consist of a route and an HTML template containing a form that prompts the user to re-enter their password in order to keep their session active. The purpose ...

Leveraging npm packages in Meteor's Angular 1.3 framework

Although it may sound like a silly question, I am still confused. It has been said that Meteor has native support for npm modules in version 1.3. I am currently using Meteor with Angular integration. From the tutorial, it appears that using npm modules sh ...

Refreshing CKFinder Form Field with jQuery

Looking to update the value of an input field .ckfinder-input using CKFinder's pop-up image selector. Everything runs smoothly until attempting to assign the selected image URL to the input field with input.val() = fileUrl, resulting in the error mess ...

Unable to hide the mobile menu button

I am currently working on a fun website project . I am facing an issue with the mobile menu button not disappearing using display:none in Safari on my iPhone when in landscape mode, even though it works fine in Chrome. My goal is to make the #menu-button ...

Navigating an Array of Objects is not functioning properly within React

In my React App, I am facing an issue with populating a key identifier. Currently, the key is based on the Object.name property, but this is not ideal as it could lead to duplications and trigger errors in React. The server does not provide a unique key ei ...

Hiding javascript code within comment tags "<!-- //-->"

Years ago, I started a practice of enclosing all my JavaScript code in files with <!-- Code goes here //--> I'm not entirely sure why I did this. Maybe it was to hide the code from old browsers, is that right? Do I still need to do this? I ...

What are the steps to execute Mike Bostock's D3 demonstrations?

I've been attempting to run Mike Bostock's See-Through Globe demonstration, but I encountered issues with the correct referencing of his json files when attempting to replicate it locally. The problem stems from this particular line of code: d3. ...

Swap the text within the curly braces with the div element containing the specified text

I have an input and a textarea. Using Vue, I am currently setting the textarea's text to match what's in the input field. However, now I want to be able to change the color of specific text by typing something like {#123123}text{/#}. At this poin ...

Unable to utilize external JavaScript files in Angular 8

I've been working on integrating an HTML template into my Angular project and for the most part, everything is going smoothly. However, I've encountered an issue where my JS plugins are not loading properly. I have double-checked the file paths i ...

Display some text after a delay of 3 seconds using setTimeOut function in ReactJS

When using React JS, I encountered an issue where I am able to display text in the console after 2 seconds, but it is not appearing in the DOM. const items = document.getElementById("items"); const errorDisplay = () => { setTimeout(function () { item ...

Vue-based bot for telegram web application

Hey there, I've been working on integrating a web app with my chat bot, taking advantage of the new Telegram feature. Unfortunately, after adding the site, I'm encountering an issue where clicking the button opens up an empty page. It seems that ...

What is the best way to trigger an event using vue-chartjs?

I am using vue js to display a graph with chartjs. I have implemented an onClick function on the graph to emit an event in the parent component and retrieve data. However, the event is not working as expected. Can you help me identify the issue? Component ...

Changing the custom route in React Router to utilize a render prop instead of the component prop

I'm currently working on a React app that incorporates React Router. I've been encountering a bug in my code stemming from my custom ProtectedRoute component: const ProtectedRoute = ({ component, ...args }) => ( <Route component={with ...

What is the process of invoking an external JavaScript function in Angular 5?

I recently downloaded a theme from this source. I need to specify script and CSS in the index.html file. The body section of index.html looks like this: <body> <app-root></app-root> <script type="text/javascript" src="./assets/js ...

Python's Selenium Throws No Such Element Exception

Looking to automate tasks involving hyperlinks on my university's SAP Portal, I decided to use Selenium. However, encountering difficulties as many web elements are dynamically generated using JavaScript, making them invisible to the webdriver. The e ...

Prevent screen from loading without JavaScript using an overlay

Is there a way to darken and lock the page, preventing clicking or scrolling, while displaying white text notifying the user that JavaScript is not enabled? I understand that the recommended approach is to gracefully degrade all elements when JavaScript i ...

Effortlessly Transition to Full Screen with Div Expansion on Click

I'm currently working on creating a smooth transition for a div to expand fullscreen when clicked. My goal is to achieve a similar effect as the case studies on this website: Although my code can make the div go fullscreen, there's an issue with ...