What is the best way to extract an array of distinct values from arrays that are nested within an array of objects

Given an array of objects like the one below:

var items = [
{item: [{foo: 21, bar: 'a' }, {foo: 5,bar: 'e'},{foo: 167, bar: 'c'}]},
{item: [{foo: 42, bar: 'a' }, {foo: 45,bar: 'd'},{foo: 7, bar: 'c'}]},
{item: [{foo: 99, bar: 'b' }, {foo: 35,bar: 'c'},{foo: 22, bar: 'e'}]},
{item: [{foo: 31, bar: 'e' }, {foo: 22,bar: 'd'},{foo: 12, bar: 'a'}]}
]

I want to create a new array that contains all unique values of the 'bar' property. So, it should look something like this:

var uniqueBars = ['a','b','c','d','e'];

Currently, my solution involves looping through all the items, but I believe there might be a more efficient way to achieve this using ES6 features.

Is there a way to generate the uniqueBars array mentioned above using ES6 functionalities?

Answer №1

To iterate through the `items` array, utilize the flatMap method. Within each inner array, use the map method to extract the value of each `bar`. After sorting the resulting flattened array, insert it into a Set to eliminate duplicates, then convert it back to an array using the spread operator in order to print the deduplicated values.

const items=[{item:[{foo:21,bar:"a"},{foo:5,bar:"e"},{foo:167,bar:"c"}]},{item:[{foo:42,bar:"a"},{foo:45,bar:"d"},{foo:7,bar:"c"}]},{item:[{foo:99,bar:"b"},{foo:35,bar:"c"},{foo:22,bar:"e"}]},{item:[{foo:31,bar:"e"},{foo:22,bar:"d"},{foo:12,bar:"a"}]}];

// For each `obj.item.map`, you will receive a nested array containing
// all bar values from each object. Apply `flatMap` on this array
// to consolidate all values into one, and then proceed to sort it
const flattened = items.flatMap(obj => {
  return obj.item.map(inner => inner.bar);
}).sort();

// Enter the flattened array into a new Set
// and spread that set into a fresh array
const deduped = [...new Set(flattened)];

console.log(deduped);

Answer №2

To retrieve the values for a Set, you can provide a sequence of keys.

const
    getValues = (data, [key, ...keys]) => data.flatMap(o => keys.length
        ? getValues(o[key], keys)
        : o[key]
    ),
    items = [{ item: [{ foo: 21, bar: 'a' }, { foo: 5, bar: 'e' }, { foo: 167, bar: 'c' }] }, { item: [{ foo: 42, bar: 'a' }, { foo: 45, bar: 'd' }, { foo: 7, bar: 'c' }] }, { item: [{ foo: 99, bar: 'b' }, { foo: 35, bar: 'c' }, { foo: 22, bar: 'e' }] }, { item: [{ foo: 31, bar: 'e' }, { foo: 22, bar: 'd' }, { foo: 12, bar: 'a' }] }],
    keys = ['item', 'bar'],
    unique = [...new Set(getValues(items, keys))];

console.log(...unique);

Answer №3

Consider this concise one-liner as a potential solution:

[...new Set(elements.map(obj => obj.element.map(o => o.foo)).flat())]

Experts @Alex and @Sara recommend utilizing flatMap() instead of [].map().flat():

[...new Set(elements.flatMap(obj => obj.element.map(o => o.foo)))]

Answer №4

To iterate through the objects array and create lookups on a new array:

Here's an example of how you can achieve this:

let uniqueBars = []; 
items.forEach((item) => {
   const existsInNewArray = uniqueBars.find(bar => bar === item.bar);
   if (!existsInNewArray) {
      uniqueBars.push(item.bar)
   }
}

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

Develop a web application in ASP.NET MVC 4 utilizing bundle configurations

At my workplace, we have an ASP.NET WebApp that utilizes ASP.NET MVC Bundles. To give you a clear picture, here is a snippet of the code: public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/bundles/jquery ...

I'm having trouble retrieving data from the server using the AngularJS $http.get() function. What am I doing wrong

Ensure that your question is clear and that your code properly showcases the issue at hand. Feel free to leave any questions or comments below for clarification. app.js var express = require('express'); var app = express(); app.use(express.sta ...

The interactive form fields are not functioning as intended due to a dynamic association issue

Issue with Adding Two Dynamic Form Fields Together I need to add two fields at once by clicking a single button, and each field should have a two-dimensional name structure like [0][0] and [0][1] for saving dual values Although I used jQuery to dyn ...

What steps should I take to fix the error "Unused left side of comma operator with no side effects.ts(2695)" in my React project?

import React from "react"; import { useRecoilState } from "recoil"; import { Industry, industryState } from "../atoms/industriesAtoms"; const manageIndustryData = () => { const [industryStateValue, setIndustryStateValue] ...

What is the method to transfer a declared object from a .ejs file to my index.js file?

I have a simple script embedded in my .ejs file. The script captures input data from the user and stores it in an object. Now, my goal is to send this object to my index.js file, where I plan to utilize the data with a node module called coap (similar to ...

What is the alternative method in JavaScript for locating items instead of using indexOf?

I have a set of paths in an array. Some paths are classified as constants while others are labeled as dynamic. A constant path would be something like "/booking-success", whereas a dynamic path could be something like '/arrival/view/:job_or ...

Reorder elements using CSS when they do not share the same immediate parent container

I am looking to rearrange the order of some items on my page using JS or CSS. The project I am working on is written with ReactJS. Here is the basic structure: <div class="parent"> <form> <div class="header"></di ...

nvim-typescript incorrectly flags non-existent type errors

I am experimenting with using neovim and have set up a minimal configuration as follows: call plug#begin() Plug 'mhartington/nvim-typescript', {'do': './install.sh'} Plug 'leafgarland/typescript-vim' Plug 'He ...

Parse the text file to extract its data and display that data in a table using Yii2 framework

Below is the javascript code used in my form: $('#idOfButton').click(function(){ var id = $('#input').val(); $.get('index.php?r=tbltime/get-file',{ id : id },function(data){ var data = $.parseJSON(data); ...

Tips on running jQuery scripts when a div changes its display style from none to block?

Is there a way to trigger jQuery code when the style of a div transitions from `display: none;` to `display: block;`? I am working with tabs, which is why this div's style changes in this manner. The jQuery code should only be executed when this spec ...

How can I create a bold, three-dimensional line using Three JS LineBasicMaterial?

Creating a new basic line material using THREE.js often does not yield the desired result. I am looking for an easy way to draw 3D lines with different colors and widths, suitable for a rotating scene. I have looked into various methods like Windows & An ...

I'm curious if there is a method to incorporate an array within a where: $or statement using sequelize?

I have an array of team IDs called teamsIdsSelected = ['1', '5', .., 'X'] In order to retrieve all the challenges associated with each team ID from the 'Challenge' table, I attempted the following: Utilizing this f ...

Undefined Laravel Product

Encountering the error message Undefined variable: $productsTR, even though I have initialized the products variable in the controller. My setup includes a main blade and a partial blade, where the main blade sends data to the controller before it is retur ...

Anticipating the execution of a loop and retrieving a value in Node.js

I am currently diving into the world of Node Js programming. I understand that javascript does not follow a sequential order and executes code synchronously which has led me to struggle with async calls. Here is the issue I am facing: Within my app.get(&a ...

Having issues with $timeout functionality in angular.js

I've implemented $timeout in my controller but it doesn't seem to be functioning correctly. app.controller("Friendsrequests",['$http','$log','$location','$timeout','$scope', function($http,$log,$ ...

`I am unable to locate the JSON file within Angular 2`

I am experiencing issues loading a .json file from a service file in my Angular2 project. I have set up my Angular2 app using angular-cli and the file structure looks like this: src > app > menu-item > menu-item.service.ts menu-list.json Bel ...

Callback for Vue asynchronous components

<template> <div> <DynamicComponentA></DynamicComponentA> <!-- Display DynamicComponentB only after DynamicComponentA is loaded --> <DynamicComponentB></DynamicComponentB> </div> ...

The decision between using multiple then statements or consolidating your code into a single then statement depends on the specific requirements

I am facing a situation where an api call returns data asynchronously and I have 2 methods that need to execute after the call is completed. However, these methods do not generate new promises on their own. Can const foo = new Promise(…); foo.then(() = ...

Creating a form submission event through Asp.net code behind

Is there a way to change the onsubmit parameter of a form in an asp.net project, specifically from the master page code behind of a child page? I am interested in updating the form value so that it looks like this: <form id="form1" runat="server" onsu ...

Validating input in Angular UI Bootstrap Datepicker

I have integrated a datepicker from angular-ui/bootstrap. However, I am facing an issue where the user can freely type in the input field instead of selecting a date. Here is a snippet of my code: session.js session.getDateFormat = function() { ...