What is the best way to eliminate duplicate values in an array's object property?

Is there a way to go through the properties of an object and eliminate duplicates from an array stored as the value for each property?

Initial object

var navObjects = {
    'Components': ['x', 'y', 'x'],
    'Document': ['z', 'z', 'z', 'q'],
    'Utilities': ['a', 'b', 'c']
}

Target object

navObjects: {
    'Components': ['x', 'y'],
    'Document': ['z','q'],
    'Utilities': ['a', 'b', 'c']
}

Approach attempted

for (let i = 0; i < Object.values(navObjects).length; i++) {

    let obj = Object.values(navObjects)[i];

    Object.values(obj).filter((item, index) => obj.indexOf(item) === index);
    console.log(obj);

}

Despite executing this code block, the arrays are not altered.

Answer №1

If you want to achieve this, you can utilize the Set constructor along with the spread syntax:

const sampleObjects = {
  'Example': ['x', 'y', 'x'],
  'Sample': ['z', 'z', 'z', 'q'],
  'Test': ['a', 'b', 'c']
};

for (const key in sampleObjects) {
  sampleObjects[key] = [...new Set(sampleObjects[key])];
}

console.log(sampleObjects);

Answer №2

This script offers a helpful solution to accomplish your goal.

let updatedNavObjects = {}
let existingObjects = {}
for(let category in navObjects) {
    let objectsList = navObjects[category];
    updatedNavObjects[category] = [];
    existingObjects[category] = {};
    for(let obj of objectsList) {
        if (!existingObjects[category][obj]) {
            existingObjects[category][obj] = 1;
            updatedNavObjects[category].push(obj);
        }
    }
}
delete existingObjects;
console.log(updatedNavObjects);

A new variable is created here for improved efficiency. Instead of using indexOf to check if a value exists in an array, the script uses a targeted key within the existObjects object for faster performance. While not the optimal solution, it gets the job done effectively. :)

Answer №3

To eliminate duplicates and convert them back to an array, you can utilize a Set and the values() method like this:

(new Set(['z', 'z', 'z', 'q'])).values()

A more organized approach is to create a reusable function:

function removeDuplicates(input) {
    return (new Set(input)).values();
}

You can then apply this function in various scenarios:

var navObjects = {
    'Components': removeDuplicates(['x', 'y', 'x']),
    'Document': removeDuplicates(['z', 'z', 'z', 'q']),
    'Utilities': removeDuplicates(['a', 'b', 'c'])
}

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

What exactly is data binding in Google Sheets all about?

Is there a way to use Google Apps Script to connect two cells together? For instance, if one cell in a sheet is modified, can it automatically update a corresponding cell in another sheet? For example, let's say in sheet1 there is a "money spent" val ...

Groupings / BespokeItems

I'm struggling to build an array with headers based on a condition, with the desired output looking something like this: $array = @() $list = "" | Select Name,Value,Status foreach ($row in $worksheet) { $row.Psobject.Properties | ? { if ($RuleA ...

What is the relationship between an odd number and the value 1 in JavaScript that results in a 'true' outcome?

I encountered a straightforward problem, but the solution has left me perplexed. function transformArray(numbers) { // If 'i' is an odd number, i & 1 will evaluate to 1 or true return numbers.map(i => (i & 1) ? i * 3 : i * 2); } co ...

When a jQuery click event is triggered, the event.target will return the child element that was clicked within the

When I have a jQuery click event assigned to a hyperlink that contains an image, each with separate ids, I expect clicking the hyperlink to trigger the code event.target.id, returning the hyperlink's id. However, it actually returns the image's i ...

What is the best way to integrate various JQuery and DataTables functionalities and organize them in a specific order

I managed to implement some features into jQuery datatables by following tutorials. However, I am struggling to combine these features and make them work together seamlessly. If you search for these features online, you will likely find where they originat ...

Error in Highcharts: The property '0' is undefined and cannot be read

Attempting to integrate data from a REST API into HighCharts, but encountering an issue: TypeError: Cannot read property 'series' of undefined. This function retrieves the data from the API: $scope.myData = function(chart) { HighCharts.query ...

Implementing a callback function in Vue js 2 for handling dispatched actions within a component

Is there a method to determine if the action dispatched from a component has completed without utilizing state management? Currently, I have an action called createAddress. In my component, there is a modal where users input their address. Once the user en ...

producing base64 encoding that results in a blank image

I have some code that is supposed to get an image from a video using canvas. However, when I save this base64 code into an image, I end up with a black image. What could be causing this issue? Here is my JavaScript code: var input = document.getElementBy ...

Adding custom script tags to a React application

I'm interested in integrating a StreamingVideoProvider video player into my React application but facing some challenges: I do not have direct access to the video URL I want to utilize their JS video player for its advanced features like password pro ...

Creating a distinct value in Master details within Angularjs

Utilizing AngularJS, I am fetching data from an API and displaying it on an HTML page. The issue arises when the SQL query, which involves a join between two tables (departments and employees), repeatedly fetches department data for each employee. My goal ...

Python does not return the AJAX request back to JavaScript unless JQuery is not utilized

I have set up an XMLHTTPrequest in my javascript code to communicate with a flask location. Here's how I am doing it: var ourRequest = new XMLHttpRequest(); ourRequest.open("GET", "makeDiff") diff = ourRequest.send(); console.log(diff); Once the req ...

Customize a div's background color with an Angular directive

Imagine having a div element: <div id="wrapper"> some text </div> How can you create an angular directive that changes the background based on user input? For instance, you might have tried: <div id="wrapper" color temperature="51"> ...

Issue with capturing mouse position in canvas when hovering over <h1> element above it

I am working on a project using React Three Fiber to animate a 3D model that follows the mouse cursor. However, I have noticed that when the mouse hovers over some divs or headings on top of the canvas element, the animation freezes and becomes choppy unti ...

Pausing and then resuming an interval function within the same function

I'm struggling with an $interval function that runs every second. The function retrieves user credentials from local storage and checks if they have expired. If they have, it refreshes them with new ones. Otherwise, it does nothing. This is what my ...

Steps for clearing the chosen input data

I am currently developing an Angular 6 application and I am working on implementing a multiple select feature using just an input box without relying on any third-party plugins, jQuery, datalist, or select boxes. The solution needs to be purely input box b ...

Priority is given to strings over numbers

Here's some code I'm working with: <tbody> <tr> <td class="float-left"> <!-- {{selectedTemplat?.modifiedAt | da ...

The issue with Angular 1.6 not displaying the scope value in the template

Hey there! I'm currently working on index.html Here's the code snippet from before: <body ng-app="MainController"> <div class="page page-base {{ pageClass }}" ng-view> </div> </div> Then, I made changes by ass ...

Rendering with ReactDom in a SharePoint Framework application

Our current project requires us to generate a PDF file using the <div></div> elements. Most of the code I've seen renders from ReactDom.Render() instead of the render class: Take for instance React-pdf: import React from 'react&apo ...

Determining the Validity of a Date String in JavaScript

I encountered an issue while attempting to validate a date string using the following code: const isValidDate = (date: any) => { return (new Date(date) !== "Invalid Date") && !isNaN(new Date(date)); } For instance: let dateStr = "some-random-s ...

Tips for adding text dynamically to images on a carousel

The carousel I am using is Elastislide which can be found at http://tympanus.net/Development/Elastislide/index.html. Currently, it displays results inside the carousel after a search, but I am struggling to dynamically add text in order to clarify to use ...