Divide the identical elements and distinct elements from a provided array into two separate arrays storing unique elements and recurring elements

Can anyone help me with this query? I have an array of objects that need to be separated into repeating and non-repeating objects based on the segments they belong to, each in a separate array. For example-

[ {name:"abc",id:1,segments:[1,2]}, {name:"abc1",id:2,segments:[1]}, {name:"abc3",id:3,segments:[1,2]}, {name:"abc2",id:4,segments:[1,2,3]} ]

The resulting unique array should be -

uniqueArr = [{ name:"abc1",id:2,segments:[1]},{ name:"abc2",id:4,segments:[1,2,3]}]

  • The example above is for non-repeating objects in the given array

repeatedEle = [[{ name:"abc",id:1,segments:[1,2]},{ name:"abc3",id:3,segments:[1,2]}]]

  • The example above is for repeating objects in the given array based on the number of occurrences of the same segments.
  • Repeated elements must be within a nested array.

Answer №1

Looking to organize arrays based on the segment prop?

Keep in mind that this solution may not be optimized for performance, but it should suffice for smaller arrays.

const data = [
  {name:"abc",id:1,segments:[1,2]},
  {name:"abc1",id:2,segments:[1]},
  {name:"abc3",id:3,segments:[1,2]},
  {name:"abc2",id:4,segments:[1,2,3]},
];

const uniqueData = data.filter((entry, idx, originalArray) => {
  const copyArray = [...originalArray];
  copyArray.splice(idx, 1);
  
  return !copyArray.some((element) => entry.segments.sort().join() === element.segments.sort().join());
});

const nonUniqueData = data.filter((entry) => !uniqueData.includes(entry));

console.log({uniqueData, nonUniqueData});

Consider this alternative approach.

const data = [
  {name:"abc",id:1,segments:[1,2]},
  {name:"abc1",id:2,segments:[1]},
  {name:"abc3",id:3,segments:[1,2]},
  {name:"abc2",id:4,segments:[1,2,3]},
];

const segmentedData = data.reduce((acc, entry, idx, src) => {

  const copyArray = [...src];
  copyArray.splice(idx, 1);
  
  const key = copyArray.some((element) => entry.segments.sort().join() === element.segments.sort().join()) ? 'nonunique' : 'unique';
  
  acc[key].push(entry);
  
  return acc;

}, { unique: [], nonunique: [] });

console.log(segmentedData);

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

Sharing data between pages in Ionic and Angular with POST requests

Currently, I am utilizing Ionic for developing a mobile application and have decided to incorporate very basic authentication (without any security measures) into the app. The process involves validating user credentials against a database through a POST r ...

Retrieve content inside an iframe within the parent container

Hey there! I've been working on adding several iframes to my webpage. Each iframe contains only one value, and I'm trying to retrieve that value from the parent page. Despite exploring various solutions on Stack Overflow, none of them seem to be ...

tracking scroll position within div on main page

I have a div tag enclosed within a content tag due to the implementation of a masterpage containing the forms and body tags. <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder2" Runat="Server"> <div id="xxx" style="overflow:s ...

What is the best approach for running a database query using the value selected from a form dropdown?

Currently, my application server is ColdFusion and I am using SQL Server for the database. Within a select form element on my webpage, users can choose from a list of vehicles such as Volvo S60, BMW M6, and VW Jetta. Once a user selects a vehicle, I need ...

How can I adjust the size of the renderer in Three.js to fit the screen?

Encountering issues with the code snippet below: //WebGL renderer renderer = new THREE.WebGLRenderer(); renderer.setSize(window.innerWidth, window.innerHeight); //TODO: set optimal size document.body.appendChild(renderer ...

The writeToDB function is triggered only one time

I've encountered an issue with my node.js code where the writeToDB function is being called, but data is not inserted in the database after the first time. Can someone help me understand why? uploadInfoObject = { ProcessId: pid, Type: "type", ...

Display all files within every subdirectory located in a specified folder on Google Drive

Recently, I stumbled upon a script located at https://github.com/bluexm/snipets/blob/master/list%20Gdrive%20files%20and%20folders. The challenge I encountered was that the script was not capable of handling folders with identical names. As a result, I made ...

Despite reaching a video readystate of 4 in HTML5, the video still hangs and does not play smoothly

Using html5, I am currently working with video and audio. I have encountered an issue where sometimes the video hangs even after its readyState === 4. The cause of this problem is unclear to me. I aim for a solution where if the video's readyState = ...

Dividing the code into a function and invoking it does not produce the desired outcome

Everything seemed to be working perfectly until I attempted to encapsulate the code into a function and call it within my expression. Unfortunately, this approach did not yield the desired results. Functional code: render: function() { return ( ...

I am interested in creating a class that will produce functions as its instances

Looking to create a TypeScript class with instances that act as functions? More specifically, each function in the class should return an HTMLelement. Here's an example of what I'm aiming for: function generateDiv() { const div = document.crea ...

The width of the plotbands on the yAxis of a stacked bar graph is adjusting as the series are dynamically toggled,

https://ibb.co/h7tmwtr https://ibb.co/syRTyPG For the first time, I have included 5 plot bands which looked great. However, when I added a series and toggled it on a stacked bar graph, the plot bands' width started increasing. I want to maintain the ...

Functionality of jQuery Mobile Page

$(document).on("pageshow", "#mappage", function (event) { $("#doldur").append("<li> <label onclick='getBina(" + featuressokak[f].attributes.SOKAKID + ");'>" ...

After reducing the size of the table, the data spills over

Hey there, amazing individuals of the internet! Hope you're all doing well today. I've encountered a rather perplexing issue that's got me stumped. So, here's the situation - I have this table full of data and I want it to initially be ...

``motioning a component beneath another component that may be in a state

Having an issue with my CSS. I have some elements generated by JavaScript and when hovering over them, another element is displayed below the others for some reason. Here's the CSS related to this problem: .hiddenTextjob { display:none; ...

Utilize AngularJS's OrderBy feature to iterate through the list for navigation in ascending order by Index

I am looking to customize the order of an Object-array using ng-repeat based on their index keys in ascending order. $scope.paneContainer = {books:[{}] } ; $scope.paneContainer.books[0].science = { title:"science", content:"web/app/views/partials/scienc ...

Develop a simple application using the MEAN stack framework

I am new to Node.js and Express and I am interested in creating a basic AngularJS application. However, I am unsure of where to begin in terms of file organization. My desired file structure is as follows: - public ----- app ---------- components -------- ...

Generating an array containing elements specified by the user's input

I am working on creating an array that can accommodate any number of elements depending on user input. The ultimate goal is to allow the user to input x amount of numbers, store them in an array, and then calculate the average. However, my current challeng ...

What's the best way to prevent extra spacing when typing in a materialUI TextField?

Instructions for the user: Please input your first name without any spaces between characters. I attempted to implement the following code, however, it did not achieve the desired outcome. <TextField required id="name" label="First Name" ...

Angular2 scripts are failing to load in the web browser

Setting up my index page has been more challenging than I anticipated. Take a look at my browser: https://i.stack.imgur.com/L4b6o.png Here is the index page I'm struggling with: https://i.stack.imgur.com/Op6lG.png I am completely stumped this tim ...

Tips for guaranteeing that the value is retained in an array when setting a Cookie in AEM/cq5

I'm facing an issue with AEM where the page path needs to be added to a cookie each time a user visits a specific type of page. The requirement is to store a maximum of 3 pages in the recently visited section of the cookie. Initially, I attempted to u ...