Tips for utilizing the method array.from and new set to efficiently return multiple values

Is it possible to extract numerous unique values from an array of objects using the Array.from(new Set) method?

For instance:

   this.data = [
  {
    "_id": "5bf57b965401169dd81c2a51",
    "age": 35,
    "name": "Paige Zamora",
    "gender": "female",
    "company": "AUTOMON",
    "reference_id": "12"
  },
  {
    "_id": "5bf57b96c2c3b88adff4b972",
    "age": 40,
    "name": "Jennifer Carr",
    "gender": "female",
    "company": "SYNKGEN",
    "reference_id": "11"
  },
  {
    "_id": "5bf57b969dd839926db78767",
    "age": 38,
    "name": "Weaver Rosales",
    "gender": "male",
    "company": "ETERNIS",
    "reference_id": "10"
  },
  {
    "_id": "5bf57b968c845ea691e76c84",
    "age": 31,
    "name": "Myers Pickett",
    "gender": "male",
    "company": "ETERNIS",
    "reference_id": "10"
  },
  {
    "_id": "5bf57b96998c44eff083d3fa",
    "age": 36,
    "name": "Dona Nicholson",
    "gender": "female",
    "company": "ETERNIS",
    "reference_id": "10"
  }
]

I want to retrieve the unique values for: reference_id and the corresponding company, resulting in:

[{12, AUTOMON}, {11, SYNKGEN}, {10, ETERNIS}]

I had considered using this approach:

const list = Array.from(new Set(this.data.map(({reference_id}) => reference_id)));

which returns:

[12, 11, 10]

Can this method be adapted to return multiple values like the list provided above?

Answer №1

To extract the desired data, consider utilizing a JSON format and then extracting the parsed values as output.

One might wonder why use a string instead of an object. The issue arises when creating new objects with similar properties; each new object is distinct rather than identical.

Set operates on either a single primitive or object and verifies if an object's reference matches. By employing a string, it enables checking the value and obtaining unique strings within the set. To achieve this, the JSON must be converted back into an object.

var data = [{ _id: "5bf57b965401169dd81c2a51", age: 35, name: "Paige Zamora", gender: "female", company: "AUTOMON", reference_id: "12" }, { _id: "5bf57b96c2c3b88adff4b972", age: 40, name: "Jennifer Carr", gender: "female", company: "SYNKGEN", reference_id: "11" }, { _id: "5bf57b969dd839926db78767", age: 38, name: "Weaver Rosales", gender: "male", company: "ETERNIS", reference_id: "10" }, { _id: "5bf57b968c845ea691e76c84", age: 31, name: "Myers Pickett", gender: "male", company: "ETERNIS", reference_id: "10" }, { _id: "5bf57b96998c44eff083d3fa", age: 36, name: "Dona Nicholson", gender: "female", company: "ETERNIS", reference_id: "10" }],
    unique = Array.from(
        new Set(
            data.map(({ reference_id, company }) =>
                JSON.stringify({ reference_id, company }))
        ),
        json => JSON.parse(json)
    );
    
console.log(unique);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

To group them in a Map without repetitions, create an array based on the string representations of reference_id and company:

var data = [{
    "_id": "5bf57b965401169dd81c2a51",
    "age": 35,
    "name": "Paige Zamora",
    "gender": "female",
    "company": "AUTOMON",
    "reference_id": "12"
  },
  {
    "_id": "5bf57b96c2c3b88adff4b972",
    "age": 40,
    "name": "Jennifer Carr",
    "gender": "female",
    "company": "SYNKGEN",
    "reference_id": "11"
  },
  {
    "_id": "5bf57b969dd839926db78767",
    "age": 38,
    "name": "Weaver Rosales",
    "gender": "male",
    "company": "ETERNIS",
    "reference_id": "10"
  },
  {
    "_id": "5bf57b968c845ea691e76c84",
    "age": 31,
    "name": "Myers Pickett",
    "gender": "male",
    "company": "ETERNIS",
    "reference_id": "10"
  },
  {
    "_id": "5bf57b96998c44eff083d3fa",
    "age": 36,
    "name": "Dona Nicholson",
    "gender": "female",
    "company": "ETERNIS",
    "reference_id": "10"
  }
];


var result = Array.from(data.reduce((accumulator, {reference_id, company}) => {
  accumulator.set(`${reference_id},${company}`, {reference_id, company});
  return accumulator;
}, new Map()).values());

console.log(result);

Answer №3

Give this a go:

this.data.map((el) =>{ return {age: el.age, company: el.company} })

// The resulting array will be:
//0: {age: 35, company: "AUTOMON"}
//1: {age: 40, company: "SYNKGEN"}
//2: {age: 38, company: "ETERNIS"}
//3: {age: 31, company: "ETERNIS"}
//4: {age: 36, company: "ETERNIS"}

{12, AUTOMON} doesn't make sense, object should be formatted as { key: value, key: value...}

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

When incorporating ng-include, the flash game graphic will have a tail, but it will be absent when not using

I successfully embedded a flash game onto my website built with Angular, Node, and Express using the angularjs media module. The code snippet looks like this: <div class="container hero-unit"> <flash width="400" height="300" src="files/avoider. ...

Array input for CodeIgniter

I'm currently working on a dynamic form where clicking the add button adds a new line to the form. However, when I try to echo the output, it's not displaying as expected. Here is my code: public function inputData(){ $provinsi = $this-& ...

The bootstrap switch button remains in a neutral grey color

Ordinary: Initially clicked: Click again: After the second click, it remains grey and only reverts on a different action like mouse click or selection. Is there a way to make it go back to its original state when unselected? ...

Why am I encountering an "Uncaught TypeError: Cannot read property 'value' of null" Error while trying to authenticate via Email?

I'm having some trouble setting up Firebase authentication using email. Whenever I click on the login button, I encounter an error message: users.js:15 Uncaught TypeError: Cannot read property 'value' of null Additionally, upon hitting t ...

What is the process for iterating through two array lists in Firestore and retrieving both the number of matched items and the matched items themselves?

In my code, I have an ArrayList where I store an array of items from a specific field in a document. I am then sending this ArrayList to another activity using the following code: Intent intent = new Intent(ProgramToProgram.this, com.example.newapp.Progra ...

Tips for arranging an array of FileInfo objects from largest to smallest without using LINQ

Unfortunately, I need to modify my code so it's compatible with NET Framework 2.0, which doesn't have support for LINQ. The current code is sorting an array of FileInfo objects based on their FullName property using LINQ, like this: Dim file ...

Updating and showing a variable in a PHP file using JavaScript within an HTML webpage

My goal is to establish a variable in a PHP file on my server named "likes." Subsequently, I wish to incorporate a like button on my HTML webpage that, when clicked, will utilize JavaScript to modify the "likes" variable in the PHP file and increase it by ...

Utilizing the zIndex property in webGL programming

I am currently working on a three.js program My main goal is to display a 2D panel in front of the three.js scene for debugging purposes. I plan to achieve this by creating a div element and adjusting its z-index to show it above the three.js canvas. Un ...

Trigger a JQuery dialog after submitting a form in MVC and pause execution until a user responds

I'm working on an MVC app that has a form. When the user clicks the 'Save' button, it should submit the form to the controller and save the changes. If certain conditions are met, a JQuery UI dialog will pop up, prompting the user for input ...

Step-by-step guide on dynamically adding "Input Tags" to the DOM at runtime using Selenium's JavascriptExecutor

In order to dynamically add the following element to the DOM during run time, I need assistance... <input type="text" name="imagesToAdd" value="3566"> My initial attempt was to use Selenium JavascriptExecutor for this task. However, I encounter ...

Upon utilizing ComponentDidMount(), a peculiar error surfaced: "Unable to invoke setState."

I encountered the following error: Attempting to call setState (or forceUpdate) on an unmounted component. This is a no-op, but it signals a memory leak in your application. To resolve this issue, cancel all subscriptions and asynchronous tasks in the ...

The React.js navigation bar hamburger menu refuses to close when toggled

Currently, my team and I have developed a react.js application together. The Navbar feature is functioning correctly, except for a small issue. When the Navbar is toggled using the Hamburger menu on a smaller screen, it opens successfully, but the toggle a ...

Exploring the parent scope in handlebars.js partials

Is there a way to access the parent scope from a partial using #each in Handlebars? Main template: (out of each = {{index}})<br> {{#each someItem}} (in each, but not on partial = {{../index}}) {{>part}} {{/each}} Partial: <div class="part ...

How can I display a calendar with a complete month view using ng-repeat?

I was trying to replicate a table similar to the one shown in this image: (disregard the styling). I am struggling with how to properly format the data to create a similar table in HTML. $scope.toddlers = [ { "name": "a", "day": 1, "total": 3 }, { ...

The datetime-picker from Twitter Bootstrap is not accurately displayed within a modal

Utilizing the twitter bootstrap datetime-picker in conjunction with Ruby on Rails has been a seamless experience for me. However, I have encountered a small issue when displaying it within a modal at the bottom of the screen. HTML <div id="datetimePic ...

Constructing items within an array literal using a constructor method

I am attempting to create an object using my Person constructor. However, I am encountering issues when I try to initialize the object directly in the array using literal notation. function Person(name, age) { this.name = name; this.age = age; } ...

What is the best way to eliminate excess elements from overflow:hidden?

Whenever I click on a modal, it changes my body to overflow:hidden. As a result, the scrollbar disappears and my page becomes unscrollable. Once I close the modal, my body reverts back to overflow:auto allowing the page to scroll again. These functionaliti ...

When submitting the form for the zip code input, use an XMLHttpRequest to input the zip code and retrieve the corresponding city

I'm currently working on a project that involves inputting zip codes and retrieving the corresponding city information from . In the future, I plan to parse this data and store it as variables in my program while potentially using longitude/latitude f ...

Looking to showcase initial API data upon page load without requiring any user input?

Introduction Currently, I am retrieving data from the openweatherAPI, which is being displayed in both the console and on the page. Issue My problem lies in not being able to showcase the default data on the frontend immediately upon the page's fir ...

Retrieving a Date object from a JSON response

Hey there, I have a situation where I'm trying to convert a JSON response into a date object in order to display it in a different format. Here's the JSON response I'm working with: responseData: [{"id":10,"createdDate":"1 Sep, 2014 12:48:5 ...