Develop an array of unique objects with multiple dimensions, ensuring no duplicates are included

Seeking assistance for the following task: I am trying to create a new multidimensional array of objects based on an existing array of objects:

[
{number:111, connectedNumber: 112, ...},
{number:112, connectedNumber: 111, ...},
{number:113, connectedNumber: 114, ...},
{number:114, connectedNumber: 113, ...}
....
]

Ultimately, I want to generate a new multidimensional array containing groups of related objects:

[
   [{number:111, connectedNumber: 112, ...}, {number:112, connectedNumber: 111, ...}],
   [{number:113, connectedNumber: 114, ...}, {number:114, connectedNumber: 113, ...}],
]

These objects are related by number === connecetedNumber.

Currently, my approach involves creating a new array and iterating through the original list of objects to check if number === connecetedNumber and then adding them to the new array:

for (let j = count; numbers.length > j; j++) {
            organizedNumber.push([numbers[j]]);

            for (let k = j; numbers.length > k; k++) {
                if (numbers[j].number === numbers[k].connectedNumber) {
                   organizedNumber[j].push(numbers[k]);
                }
            }
        }

However, this results in a new array structured like this:

[
   [{number:111, connectedNumber: 112, ...}, {number:112, connectedNumber: 111, ...}],
   [{number:112, connectedNumber: 111, ...}],
   [{number:113, connectedNumber: 114, ...}, {number:114, connectedNumber: 113, ...}],
   [{number:114, connectedNumber: 113, ...}],
....
]

The loop is iterating over each element as expected, but it also adds elements that have already been included in the previous array.

If you have any suggestions or guidance, please let me know. Thank you.

Answer №1

One option is to search for the desired group and then either include the item in that group or create a new group.

let data = [{ number: 111, connectedNumber: 112 }, { number: 112, connectedNumber: 111 }, { number: 113, connectedNumber: 114 }, { number: 114, connectedNumber: 113 }],
    grouped = data.reduce((result, obj) => {
        const
            checkCaseA = a => a.some(({ number }) => obj.connectedNumber === number),
            checkCaseB = a => a.some(({ connectedNumber }) => obj.number === connectedNumber),
            tempArray = result.find(checkCaseA) || result.find(checkCaseB) || [];

        if (!tempArray.length) result.push(tempArray);
        tempArray.push(obj);
        return result;
    }, []);

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

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

Angular select tag failing to display input data accurately

When constructing select type questions for my web app using a JSON file, the code snippet for the select tag appears as follows: <div class="form-group" ng-class="{ 'has-error': form.$submitted && form[field.id].$invalid }" ng-if="fi ...

Creating dual permission menus for two different roles in Vue JS 3

This is my router file checking which role is logged in: router.beforeEach((to, from, next) => { if (to.matched.some(record => record.meta.requiresAdmin)) { if(VueJwtDecode.decode(localStorage.getItem('accessToken')).sub == &quo ...

Difficulty with Nuxt + Vuex: Retrieving data from state using getter

Can anyone assist me with this issue? I am having trouble with my getters in Vuex not recognizing the state. Here is the code snippet: https://codesandbox.io/s/crazy-moon-35fiz?file=/store/user.js user.js: export const state = () => ({ user: { is ...

Client-side image upload problem in Next.js API routes

I've been banging my head against this bug for a couple of hours now and I just can't seem to figure out the reason behind it. The issue is with an API route I'm trying to set up in next.js where I need to modify an image and then upload it ...

Issue: jQuery 1.9 causing freezing in Internet Explorer 9 following initial $ajax request

When creating a dynamic webpage, I encountered an issue with Internet Explorer hanging after the first request when using Ajax Long Polling with jQuery 1.9. The script code I implemented is based on this article: Simple Long Polling Example with JavaScrip ...

Import an array in Python from a text file formatted in ASCII style

Inside the file named "array.txt", there is a 5x5 array of two-digit numbers presented as follows: +-------------------------+ ¦ 34 ¦ 21 ¦ 32 ¦ 41 ¦ 25 ¦ +----+----+----+----+-----¦ ¦ 14 ¦ 42 ¦ 43 ¦ 14 ¦ 31 ¦ +----+----+----+----+-----¦ ¦ ...

How can I change "Thu Sep 19 14:24:59 UTC 2019" into a moment date?

Struggling to convert this date: created_at= "Thu Sep 19 14:24:59 UTC 2019" I attempted to use the following code: let elementDate=moment(created_at) However, I keep receiving an error message: moment.invalid(/* Fri Aug 30 09:52:04 UTC 2019 */) I als ...

After performing an action with Redux, the error message ""Cannot access properties of 'undefined'" is displayed

I am currently developing a Shopping List App using React/Redux. I am facing issues with removing items from a list. When I trigger the 'removeItem' action, the page no longer recognizes the object that represents the list (which was originally s ...

Create a continuous scrolling tool similar to Google Reader for iGoogle

Do you know how to create an infinite scroll widget similar to Google Reader on iGoogle? This widget should be able to dynamically load data as the user scrolls, and replace the traditional scroll bar with a pair of up and down arrows. The HTML structure ...

Enhancing the Efficiency of JavaScript's indexOf Method

I am currently developing a basic search algorithm in JavaScript. var title = "Discovering the Best Book of All Time"; var search1 = "of DiscoverinG boOk Best"; var search2 = "Of TIme best all" var search3 = "Book discovering time" When using indexOf(), ...

Using Webdriver to dynamically enable or disable JavaScript popups in Firefox profiles

I am currently working on a test case that involves closing a JavaScript popup. The code functions correctly in a Windows environment, but when I try to deploy it on a CentOS based server, I encounter the following error: Element is not clickable at point ...

Combine arrays using union or intersection to generate a new array

Seeking a solution in Angular 7 for a problem involving the creation of a function that operates on two arrays of objects. The goal is to generate a third array based on the first and second arrays. The structure of the third array closely resembles the f ...

Creating dynamic properties in JavaScript based on another object is a powerful way to manipulate data

In my current scenario, I am faced with the task of creating a new object named result based on an existing object called source. This new object must contain all properties from source, and also include additional "methods" named after the properties to ...

"The Promise in the AngularJS Karma test specification did not resolve and the .then() method was not invoked

An issue arises when attempting to perform AngularJS Karma Unit Testing on a service. The service includes a method like the one below: service.getIntersectingElements = function (element, elements) { var deferred = $q.defer(); var tolerance = 20 ...

Is there a more efficient way to optimize my coding for this Cellular Automata project?

As a beginner in programming, I wanted to delve into the world of cellular automata and decided to create my own using JavaScript. The project involves a simple binary (black and white) 2D CA where each cell updates its color based on the colors of its 8 ...

Tips for displaying a JSON array on a web browser using a React component

My goal is to display a list of JSON data obtained from an API on the browser. I have successfully fetched the data from the REST API in the backend and now need to render it on the browser. Here is what I have learned and attempted: import React from &ap ...

The Textfield component in Material UI now automatically sets the default date to the current date when using the "date" type

I am using Material UI's textfield with the type set to "date" and I'm experiencing an issue where the date defaults to the current date instead of mm/dd/yyyy. Is there a way to prevent this behavior and display mm/dd/yyyy when the user loads the ...

determine the color of the pixel at the top left corner of a jpg image

If we were given a specific URL, for instance, "//upload.wikimedia.org/wikipedia/en/a/a9/Example.jpg", how can we use javascript (specifically jQuery or Angular) to obtain the top left coordinates (or any (x,y) coordinates) of this image? Just to clarify, ...

Adjust the color of the input range slider using javascript

Is there a way to modify the color of my slider using <input type="range" id="input"> I attempted changing it with color, background-color, and bg-color but none seem to work... UPDATE: I am looking to alter it with javascript. Maybe something al ...

What could be causing the inability to 'GET' a page on an express app?

As a beginner in web app development, I've been self-teaching Node Express. While I've had success running simple express apps on Cloud9 environments, I'm facing difficulties getting them to work with VS Code. The server starts up fine, but ...