What is the best method for retrieving unique property values from an array?

Help needed with this array manipulation task:

var arr = [{id:"1",Name:"Tom"},
           {id:"2",Name:"Jon"},
           {id:"3",Name:"Tom"},
           {id:"4",Name:"Jack"}]

I want to extract unique Names from the above array.

var result = getUniqueNames(arr);

The final result should be:

 ["Tom","Jon","Jack"]; 

Can anyone guide me on how to achieve this task effectively?

Answer №1

When Set is at your disposal, you can achieve the desired outcome with ease:

new Set(arr.map(item => item.Name))

(you can convert the set to an array by passing it to Array.from)

Answer №2

One way to achieve this is by utilizing the Set object

const arr = [
   { id: "1", Name: "Tom" },
   { id: "2", Name: "Jon" },
   { id: "3", Name: "Tom" },
   { id: "4", Name: "Jack" }
];

const uniqueNames = [...new Set(arr.map(item => item.Name))];

console.log(uniqueNames);

Alternatively, you can loop through the array and implement a condition to extract only the unique names.

const arr = [
   { id: "1", Name: "Tom" },
   { id: "2", Name: "Jon" },
   { id: "3", Name: "Tom" },
   { id: "4", Name: "Jack" }
];

const uniqueNames = arr.reduce(function(arr, item) {

   if(arr.indexOf(item.Name) === -1) {
      arr.push(item.Name);
   }

   return arr;

}, []);

console.log(uniqueNames);

Answer №3

give this a shot

let data = [{
        id: "1",
        name: "Sara"
    }, {
        id: "2",
        name: "Mike"
    }, {
        id: "3",
        name: "Sara"
    }, {
        id: "4",
        name: "Emma"
    }]

    function getUniqueNames(data) {
        let uniqueArray = [];
        data.forEach((item, index) => {
            uniqueArray.push(item.name)
        });
        return uniqueArray
    }
   let newUniqueArray =  getUniqueNames(data)

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 are the steps for translating multiple meshes in various directions using three.js?

One issue that I am encountering involves creating 100 meshes with a for loop, all of which have the same position coordinates of 0,0,0. I would like these meshes to move in different directions individually. Below is my code for creating the 100 meshes: ...

Do we need to include href in the anchor tag?

Why am I unable to display the icon within the <anchor> element without using the href attribute? The icon only appears when I set the href attribute to "". Even if I manage to show the icon by adding href="", adjusting the size with width and height ...

The use of backticks within an HTML document for nesting purposes is not permitted

Currently, I am utilizing nodemailer to send HTML template code in Node.js. However, the issue I am encountering is that I cannot nest backticks within it: Here's my code snippet: let mailDetails={ from: 'example@example.com', to: & ...

Monitor the x and y positions for platformer game interactions using only JavaScript and jQuery

I am currently working on a 2D platformer game as part of my college project alongside my friends. We are using jQuery and pure JS for development. So far, we have been able to move the character left and right using jQuery's animate function, and ena ...

obtain the present date using JavaScript

I am currently utilizing the Datetimepicker developed by XDAN. My goal is to have the current date set as the default when the page loads. To achieve this, I attempted using the new Date() along with the getUTCFullYear functions. However, there's a ...

Presenting a dynamic selection of files from a database in a dropdown menu with looping functionality using Laravel

I have a dropdown menu that I want to use to display input files from the database based on the selection made. Here is the scenario: When a dropdown option is chosen, it should show input files derived from the "loop_atachment" table (based on the select ...

Creating a virtual reference in Mongoose that connects two ObjectIds

Is it possible to establish a virtual reference using a local ObjectId to a foreign ObjectId, or can it only be done with a local _id? I'm troubleshooting to determine if there's an issue causing this not to work as expected. const Post = new mo ...

Executing multiple child processes in a loop with asynchronous operations and collecting the output after the loop concludes

Here's a snippet of code I've been working on... const { exec } = require('child_process'); const Main = async () => { const result = await RetrieveAllItems(); console.log('output', result); }; const RetrieveAllI ...

Updating data in React using a specific API call and implementing routing functionality

Currently immersed in learning React, I've developed my initial web application - a simple page that fetches API data on Covid-19 for the USA and categorizes it accordingly. To achieve dynamic content display, I utilized React Router along with the da ...

Chai spy does not recognize sinon stubbed functions when verifying function calls

I am working with two asynchronous functions that return bluebird promises: Async1: function() { return new Promise(function(resolve, reject) { execute(query) .then(function(resp) { resolve(resp); }) .catch(function(err) { ...

Toggle visibility between 2 distinct Angular components

In my application, I have a Parent component that contains two different child components: inquiryForm and inquiryResponse. In certain situations, I need to toggle the visibility of these components based on specific conditions: If a user clicks the subm ...

Searching for text within an object using MongoDB's text search feature

I am having trouble configuring a search functionality for MongoDB on my API, specifically focusing on the location object in the model provided below. I encountered an error while attempting to set up the text search in the database as shown. Can you he ...

I would like to know how to calculate monthly snowfall using numpy

I have a dataset containing daily snowfall records for one year. The date variable is in the YYYYMMDD format. Date Snow 20010101 0 20010102 10 20010103 5 20010104 3 20010105 0 ... 20011231 0 You can access the actual data here. My task is to d ...

Angular.js enables seamless synchronization between contenteditable elements and the $scope object by automatically updating the

I'm completely new to Angular.js and have been exploring various tutorials to grasp the concept of two-way binding with contenteditable elements within an ng-repeat. Currently, I am utilizing a shared 'store' between controllers like this: ...

Updating the span element upon click in jQuery

I have this JavaScript code snippet that I am working with: $('a').click(function() { $('a span').first().toggleClass('hide'); $('a span:nth-child(2)').toggleClass('display'); }); .hide { display:none; ...

"Implementing bubble sort on an array of strings using strcmp function in C is not yielding the

I've been attempting to organize a string array in C (char**), where the string array represents all the file names within a directory. Below is the code snippet that should sort the array alphabetically, however, it's not functioning as expected ...

What is the reason for the 'scrollHeight' being considered 'undefined' in this particular scenario, and why did the iframe encounter an error when switching to the html-file?

This is my first time asking a question, so please forgive any mistakes... I am attempting to create a website using HTML, CSS, and JavaScript on my Raspberry Pi with Apache2. I have written a script for an automatic iframe height function based on the co ...

The current date object in JavaScript will only display the year or a combination of the month and

$scope.articles = [ { link: "http://google.com", source: "Google", title: "hello", "date": new Date(2008, 4, 15) }, ]; <tbody> <tr ng-repeat = "article in articles | orderBy:sortType:sortReverse | filter:searchArticle ...

Bootstrap5: Left-aligned Navigation Bar Pills and Right-aligned Text

I am trying to align all my navigation pills to the left, and then add a single text element that stays at the end of the navbar even when the page is resized. Navbar Image My attempt involved adding a div so that the navbar pills would take up 50% width ...

Is there a way to find keys with matching values within a dictionary?

In my dictionary, I have two sets of identical array values for different keys. My query is: How can I determine which keys have the same value based on inputting just one value? I want to retrieve all keys that share the same values as an output. This i ...