Unlocking the values of a property from an array of objects in JavaScript

I am faced with an array that has the following structure:

const array = [
    { id: "LAX" },
    { id: "BAS" },
    { id: "TES" },
    { id: "LAX" },
    { id: "LAX" },
    { id: "ATL" },
    { id: "BNA" },
    { id: "LAX" },
  ];

I have been attempting to eliminate duplicate values of id using Set

[...new Set(array)]

This method is not proving to be effective at the moment.

My goal is essentially to achieve a final outcome resembling the following:

["LAX", "BAS", "TES"....] // without any duplicates.

Do you know of any ES6 solutions for this issue?

Answer №1

If you want to efficiently create your data using a Set, it's important to first map your data according to a specific key. This simple solution can help:

const array =[
  {id: "NYC"},
  {id: "CHI"},
  {id: "MIA"},
  {id: "NYC"},
  {id: "NYC"},
  {id: "LA"},
  {id: "SF"},
  {id: "NYC"}]
const result = [...new Set(array.map(item => item.id))]

Answer №2

I believe this code snippet could be the solution you're looking for.

const elements = [
  { id: "NYC" },
  { id: "CHI" },
  { id: "SF" },
  { id: "NYC" },
  { id: "NYC" },
  { id: "LA" },
  { id: "MIA" },
  { id: "NYC" },
];
const uniqueElements = new Set();
elements.forEach((item) => uniqueElements.add(item.id));
const uniqueArray = Array.from(uniqueElements);

Answer №3

let items = [{
    name: "Apple"
  },
  {
    name: "Banana"
  },
  {
    name: "Orange"
  },
  {
    name: "Apple"
  },
  {
    name: "Apple"
  },
  {
    name: "Peach"
  },
  {
    name: "Grape"
  },
  {
    name: "Apple"
  }
];
const uniqueItems = [...new Map(items.map((item) => [item.name, item])).values()];
console.log(uniqueItems)

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: The application has encountered an error due to an undefined property reading issue, resulting in a type error

Here is the code for the company.ts file: company.ts file - List item export class Company{ gstNo:number; contactNumber:number; contactName:string; phoneNo:number; address:string; companyName:string; } import { Injectable } ...

ng-click - triggers a function and then redirects to another page

I'm facing a small issue. I am trying to set up an ng-click event that redirects, but before the redirect happens, I need to send some data through post request. Here is my HTML code : <a href="/test" ng-click="updateData($event)">Go</a> ...

NodeJS - Headers cannot be modified once they have already been sent to the client

I've recently discovered a solution to the issue I was facing, which involves adding a return statement after sending a response. However, despite implementing the return statement, the error persists. const dbEditCourse = (req, res, db, logger) => ...

Unable to modify the ID of the initial element in the <template> tag

Here is the HTML template that I need help with: <template id="single_feed"> <div class="ibox" id="FIRST_DIV"> <div class="ibox-title"> <h5 id="naslov"></h5> </div> <div clas ...

The GIPHY API object returns no results

Utilizing Angular 2 to fetch data from the GIPHY API. export class ListaGifsComponent { gifs : Object[] = []; urlBase = "http://api.giphy.com/v1/gifs/search?q="; termoPesquisado = "ryan+gosling"; key = "O8RhkTXfiSPmSCHosPAnhO70pdnHUiWn"; ...

Issues with UA PhoneGap 2.0 plugin failing to initialize properly on iOS device

In my attempt to integrate push notifications into my iOS PhoneGap 2.0 app using the recently released Urban Airship plugin, I encountered an issue. Everything functions perfectly when I load the index.html from the provided sample application into my proj ...

Exploring React-Redux: The Origin of Children Components

Currently, I'm following a tutorial on react-redux which can be found at the following URL: http://redux.js.org/docs/basics/ExampleTodoList.html As I analyze the code in link.js, I'm curious about the source of the {children} element. import R ...

Include the array in the 'content' property of the CSS using Jquery

I need help formatting data in CSS. The code I have is as follows: if (ext){ switch (ext.toLowerCase()) { case 'doc': pos = 'doc'; break; case 'bmp': pos = 'bmp'; break; ...

Ensure that each of the two divs maintains a 16:9 aspect ratio, and utilize one div to fill any remaining empty space through the

This layout is what I am aiming for: https://i.sstatic.net/uZdty.png While I can achieve a fixed aspect ratio with a 16:9 image by setting the img width to 100%, I run into an issue where the height scaling of flexbox becomes non-responsive. The height re ...

The JSON formatting is incorrect

When I receive a Json object from an api call, the keys and values are separated. I have attempted to find a solution, and it currently looks like this: { "range": "'1'!A1:AM243", "majorDimension": "ROWS", "values": [ "DeptID", ...

Determine the scale and position adjustments by assessing the pageYOffset

Currently, I am faced with the following dilemma: I possess an object along with its initial position; Upon the initiation of page scrolling, my goal is to have this object move downwards towards the center. Once the scroll reaches 100vh (referred to as ...

What is the most effective method for preserving RichText (WYSIWYG output)?

I am currently using a JavaScript-based rich text editor in my application. Could you suggest the most secure method to store the generated tags? My database is MySQL, and I have concerns about the safety of using mysql_real_escape_string($text);. ...

Constructing a table in React using columns instead of the traditional rows

Currently tackling a project in react, I am looking to construct a material-ui table with specific characteristics. Within my array of elements, each element represents a column in the table and contains a name and the number of cells it covers. For examp ...

Error: Webpack has encountered difficulty in resolving a third-party module

I am currently utilizing the compact/angular-bootstrap-lightbox library in a project where I am transitioning from RequireJS to webpack. I have encountered an error and I am uncertain whether it is due to my configuration or an issue with the module itself ...

Looking for the most effective method of defining multiple configurations in a multi-build Vue js application?

I am currently developing a Vue 3 web application that is intended to be deployed for various customers, each with their own unique title, logo, and icon. My goal is to customize the app for each customer by displaying their specific information in the ...

How to make a node_module global with the power of Webpack 2

I'm currently utilizing a package in an Angular project that can be found at the following link: https://github.com/pablojim/highcharts-ng One of the requirements for this package is that highcharts needs to be included as a global dependency by add ...

Error: Attempting to access properties of an undefined variable (specifically 'document') is not allowed

The other day, while working on a project, I encountered an issue with my GraphQL implementation using the JavaScript graphql-request library. Here is the snippet of code that caused the error: import { request, gql } from 'graphql-request' const ...

Is it possible to update table cell content depending on selected option?

Displayed here is the select block: <form> <select id="select"> <option disabled selected value="choose"> CHOOSE </option> <option value="i2g" id="i ...

Tips for concealing overlay when the cursor hovers

Can anyone help me with a code issue I'm having? I want to hide an overlay after mouse hover, but currently it remains active until I remove the mouse from the image. Here is the code: .upper {position: absolute; top: 50%; bottom: 0; left: 50%; tra ...

`What is the best way to access value during an onChange event?`

I'm currently utilizing react-input-calendar for my project. My goal is to extract the date value from the onChange event and then transfer it to a new page. Can someone provide guidance on how to achieve this? Here is the code snippet: constructor( ...