Comes equipped with functionality for array within an array

I have an array of arrays.

m = [[-100,100], [-100,-100], [-100,-100], [-100,100]]

Removing duplicates in this array has proven tricky for me. I attempted to use:

 aa = [...new Set(m)];

// and 

let chkdup = (arr, tar) => tar.every(v => arr.includes(v))`. 

Unfortunately, I was not successful in removing the duplicates using these methods.

In Python, checking for duplicates is straightforward with [-100,100] in m. However, I am unsure of the equivalent function in JavaScript. The includes method does not seem to work in this case.

Answer №1

The reason behind this issue is that [-100, 100] != [-100, 100]. To resolve this, one approach is to convert the arrays into strings and then compare the strings using JSON.stringify.

let arr = [[-100,100], [-100,-100], [-100,-100], [-100,100]]
arr = arr.map(item => JSON.stringify(item).trim()) // Convert to string format
arr = [...new Set(arr)] // Remove duplicates by converting to array
arr = arr.map(item => JSON.parse(item)) // Parse back to objects

It's important to note that while this solution may not be the most efficient (due to the need for converting to and from strings), it is a straightforward method. This comparison method works specifically with comparing the JSON strings of two objects and will not function properly with custom classes.

Answer №2

One reason why new Set may not work as expected is due to the fact that in JavaScript, arrays with identical values are not considered equal. For example, running

console.log([-100,100] == [-100,100]);
will return false. If you need assistance comparing arrays, you can check out this helpful post.

An effective workaround involves converting subarrays into strings and then leveraging Set for deduplication:

const arr = [
  [-100, 100],
  [-100, -100],
  [-100, -100],
  [-100, 100]
];

const setArray = new Set(arr.map(x => JSON.stringify(x)));

const result = [...setArray].map(x => JSON.parse(x));

console.log(result);

If you're looking for a simpler solution, using Lodash uniq could be a viable option.

Answer №3

Using JavaScript, you can achieve this by utilizing the Set and map functions to parse the value. For further details, refer to this article on Map with Set.

 m = [[-100,100], [-100,-100], [-100,-100], [-100,100]];
 result = Array.from(new Set(m.map(JSON.stringify)), JSON.parse);
 console.log(t);

Answer №4

To transform arrays into strings, use the .map() method with JSON.stringify(), then input them into a set. By converting the array elements into strings, the set can effectively eliminate duplicates by comparing for equality. Next, utilize Array.from with a mapping function of JSON.parse to revert it back into an array of arrays:

const arr = [[-100,100], [-200,-200], [-100,-150], [-175,125]];
const result = Array.from(new Set(arr.map(JSON.stringify)), JSON.parse);
console.log(result);

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

compile a list of all class elements in the posts array

There are several elements on a page that I am working with. Using Jquery toggle, I am able to toggle a class on and off as needed. Now, I need to pass a PHP array with the names of all elements that have been toggled on. Initially, my solution was to cre ...

What are the best ways to maximize a web worker's ability to handle multiple tasks at once

I'm currently working on implementing a Web-Worker to handle its state while also managing multiple asynchronous requests. worker.ts file let a =0; //state of the worker let worker=self as unknown as Worker; worker.onmessage =(e)=>{ console ...

Unable to transfer object from Angular service to controller

I am currently utilizing a service to make a $http.get request for my object and then transfer it to my controller. Although the custom service (getService) successfully retrieves the data object and saves it in the responseObj.Announcement variable when ...

Explore the wonders of our solar system using three.js!

I am embarking on my first project using three.js to create a miniature solar system consisting of 1 star, 2 planets, and 1 moon orbiting each planet. As a beginner to both three.js and JavaScript in general, I am eager to learn. Currently, I have success ...

404 Error: JSON POST and GET Request Not Located

I need assistance with setting up an API in Django as I am encountering errors in the JavaScript console. The error messages are: GET http://127.0.0.1:8000/edit/undefined 404 (Not Found) POST http://127.0.0.1:8000/edit/undefined 404 (Not Found) Is there a ...

capture standard output from chunks during execution

When attempting to utilize execFile to log the percentage completion of a task in the standard output, I encountered an issue with the callback function: var child = require('child_process'); child.execFile("path/to/the/file", options, function ...

Tips for avoiding the 'ResizeObserver loop finished with unhandled notifications.' error when using React with mui/material/Table

This is our current code snippet: import Table from '@mui/material/Table'; import TableBody from '@mui/material/TableBody'; import TableCell from '@mui/material/TableCell'; import TableContainer from '@mui/material/TableC ...

How to set up objects with accessors and mutators in ES5 JavaScript?

creating a new object, obj1, with an enumerable property of value 42 > changing the value of obj1.property to 56 > output: 56 > accessing obj1.property returns: 42 When using use strict, an error occurs. To merge multiple objects: using jQuery ...

How to utilize Vue.js method to retrieve child prop?

In my Vue.js project, I have created two components. The main component uses a child component called NoteRenderer, which includes a prop named data_exchange. My goal is to update this prop from the main component when a button is clicked. I attempted to a ...

What is the best way to retrieve the top N ARRAY_MAX values in a SQL query

I have a table with a column that is an array type, and each row contains an array of length 100. I am trying to extract the top 10 values from each array, but I only know how to retrieve the top 1 value using ARRAY_MAX(column). Is there a way to get the ...

Ways to minimize the number of movement operations within an array

If I have an array of numbers, like [0, 1, 2, 3, 4, 5], and my goal is to rearrange it to become [2, 1, 4, 0, 5, 3], I am only able to use a single method: move(fromIndex, toIndex) To reach the desired array, I need to execute the method multiple times: ...

unable to clear form fields after ajax submission issue persisting

After submitting via ajax, I am having trouble clearing form fields. Any help in checking my code and providing suggestions would be greatly appreciated. Here is the code snippet: jQuery(document).on('click', '.um-message-send:not(.disabled ...

Will the error function of Ajax have any impact, or just the success part?

I am new to JavaScript and currently working on a view where the submit button should save data. If the textboxes are empty, there should be an error message displayed using Bootstrap alert. However, in all cases, only the success alert pops up, even when ...

Tips on pausing until another function completes using async functions

Is there a way to ensure that my Angular functions are executed sequentially in the ngOnInit() lifecycle hook? I attempted to use async, but it didn't work as expected... nbPage() getAllCommerces(page) sort() getCommerces(isFirstLoad, event) import ...

Unable to effectively select all checkboxes using jQuery

I can't seem to figure out why my code isn't working and I need help. My goal is to select all checkboxes when clicking on "Todas". I created a JSFiddle demo where the code works perfectly. However, when I implement it in my project, it fails w ...

What sets apart importing components in computed from importing components in dynamic import in Vue.js?

Imagine there are 4 components available on a page or within a component, and the user can utilize them based on their selection by toggling between Input, Image, Video, or Vudio components. There are two ways to lazily load these components: 1) <temp ...

At which location do you configure the applicationIconBadgeNumber?

Can anyone guide me on how to set up the applicationIconBadgeNumber for a React Native / Expo application on both iOS and Android platforms? I am currently using React Native, Visual Studio Code, and Expo. Where should I look to configure this feature? O ...

Calculate the sum of the elements within an array that possess a distinct attribute

I need to calculate the sum of certain elements in an array. For example, let's consider this array: var sampleArray = [ {"id": 1, "value": 50, "active": true}, {"id": 2, "value": 70, "active": false}, ...

Attempting to include a navigation bar within the footer section of my layout page - the master page on my website

Is there a way to add a navigation bar in my footer on the layout page without having to add it to every individual page? I want the icon color for the active page to be red, but only apply this to the current page and not all pages. Currently, when I nav ...

Restrict HTML Content in Json Result using PHP and Jquery

I'm currently working with a Controller that outputs JSON response and a JavaScript function that appends that response to the last tr in an HTML table. <pre> $reponse="<tr class=\"border_bottom\"><td>My Repo ...