Improved method for flattening arrays

Attempting to extract objects from an array to a new array. Searching for a more efficient method.

Approach used: Created a new array with filter1, flattened it, then created another array with filter3.


filter1 = myArray.map((a => a.courseEnrolled);
filter2 = filter1.flat(1);
filter3 = filter2.map((a => a.course);

In search of a better solution to achieve the same result.


myArray = [
{
name: "john",
courseEnrolled: [
{
course: {
name: "react",
},
},
{
course: {
name: "java",
},
},
],
},
{
name: "Doe",
courseEnrolled: [
{
course: {
name: "java",
},
},
{
course: {
name: "angular",
},
},
],
},
];

expectedArray = [
{
name: "react",
},
{
name: "java",
},
{
name: "java",
},
{
name: "react",
},
];

uniqueExpectedArray = [
{
name: "react",
},
{
name: "java",
},
{
name: "react",
},
];

Answer №1

Utilize a combination of flatMap() and nested map() functions to extract all the name's

Next, identify all the distinct values, then employ map() to transform them into the final object

myArray = [{name: "john", courseEnrolled: [{course: {name: "react", }, }, {course: {name: "java", }, }, ], }, {name: "Doe", courseEnrolled: [{course: {name: "java", }, }, {course: {name: "angular", }, }, ], }, ];
    
const all = myArray.flatMap(e => e.courseEnrolled.map(c => c.course.name));
const res =  all.filter((v, i, s) => s.indexOf(v) === i).map(name => ({ name }));
console.log(res)

[
  {
    "name": "react"
  },
  {
    "name": "java"
  },
  {
    "name": "angular"
  }
]

Answer №2

Here is a handy code snippet for you:

transformedArray = myArray.map(item => item.courses.map((course) => course.name)).flat(4)
filteredUniqueArray = [...new Set(transformedArray)].map((name)=>{  return { "name" : name} })

I trust this solution will be of use to you! Feel free to ask if you have any queries or uncertainties.

Answer №3

Could you please use Lodash?

const  myList = [{name: "alice",courseEnrolled: [{course: {name: "python"}},{course: {name: "javascript"}}]},{name: "Bob",courseEnrolled: [{course: {name: "c++"}},{course: {name: "ruby"}}]}];

const result = _(myList)
  .flatMap(({ courseEnrolled }) => courseEnrolled.map(({ course }) => course))
  .uniqBy('name');
  
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0 }
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5b37343f3a6d">[email protected]</a>/lodash.min.js"></script>

Answer №4

Here's a concise solution that does the trick

const data = [{name: "Alice", courses: [{course: {name: "react"}},{course: {name: "java"}}]},{name: "Bob", courses: [{course: {name: "java"}},{course: {name: "angular"}}]}];

const courseNames = Object.keys(data.reduce((acc, { courses }) => {
  courses.forEach(({ course }) => acc[course.name] = true);
  return acc;
}, {}));

console.log(courseNames);
.as-console-wrapper { max-height: 100% !important; top: 0 }

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 is the method to incorporate the current time into a date object and obtain its ISO string representation?

I'm using a ngbDatePicker feature to select a date, which then returns an object structured like this: {year:2020, month:12, day:03} My goal is to convert this date into an ISOString format with the current time. For example, if the current time is 1 ...

What is the best way to organize objects in a 2D game?

I am currently working on a unique perspective-based 2D/3D game using javascript. In the image below, you can see the X and Y-axis that I have implemented for this project. My question: On the map, I have several objects labeled as "1" and "2" with prope ...

Revising the $.parseJSON Function in jQuery 1.9.1 to Match jQuery 1.8.3's Implementation

With the latest version of jQuery, 1.9.0, there have been changes in the implementation of $.parseJSON which is causing some issues for us. We relied on how earlier versions of jQuery handled null and empty strings, where it would return a null value inste ...

The retrieval of data from AWS Dynamodb in Node.js is not done synchronously

I recently started working with Node.js and DynamoDB. I created a Node.js SDK to retrieve a single row from a DynamoDB table. The data is being fetched correctly, but there is a delay which is causing an error. Below is a snippet of my code: var AWS = re ...

Error encountered when utilizing the Xceed PropertyGrid with an array of System.Windows.Media.Color resulting in a Null

I am encountering an issue with my object while using a PropertyGrid, where I receive a NullReferenceException when attempting to access the Color[] property. The stack trace displays: System.NullReferenceException: Object reference not set to an instanc ...

What is the method for setting a default image to be preloaded in filepond?

Currently, I am working on a Laravel view for editing a record which includes an associated image. My goal is to have the image preloaded inside the input file so that when you submit the form, the same image is sent or you can choose to change it. // Con ...

axios GET and POST requests are not functioning properly, while fetch requests are successful

I recently set up a REST API on Heroku using Express, NodeJS, and MongoDB (mogoose as orm and MongoDB Atlas as well). I am diving into the world of MERN stack development as a beginner ...

Converting a Single Array into a Multidimensional Array using PHP

As a PHP newcomer, I am tasked with sending data to an API. The array print_r($detail) has the following structure: Array ( [0] => Array ( [id] => item1 ) [1] => Array ( [price] => 300 ...

Enhance User Experience with the Tooltip Feature and Customized

Here is the jQuery code I am using to style my tooltips: $(function() { // select all input fields within #tooltips and attach tooltips to them $("#tooltips :input").tooltip({ // place tooltip on the right edge position: "cen ...

Integrate PHP code into a div using Javascript and Ajax without losing any previous inclusions

Having issues with my navigation bar and elements. <ul><li> The element in question is: <li> My elements are linked via ajax to a separate php function file: switch ($_GET['menu']){} The functions are separated on a php fi ...

What is the process for configuring my CSS and JS files to send HTTP response headers?

During our security evaluation of a web application built in Laravel 4, we discovered that the Anti-MIME-Sniffing header X-Content-Type-Options was not properly configured to 'nosniff'. The following PHP code snippet sets the necessary HTTP heade ...

What is the best way to deliver static HTML files in Nest.js?

I am encountering an issue with loading JS files from a static /dist folder located outside of my Nest project. While the index.html file loads successfully, any JS file results in a 404 error. In another Node/Express.js project, I am able to serve these ...

Iterating through an array with a .forEach loop and referencing the variable name

Currently, I am working on a project using JS/React and dealing with nested arrays in an array. The structure of my data looks like this: const ezra = ["Patriots", "Bears", "Vikings", "Titans", "Jets", "Bengals"] const adam = ["Chiefs", "Cowboys", "Packer ...

Unable to dynamically update properties in CSS and JavaScript without refreshing the page

I've tried applying active properties in my CSS and JavaScript, but it doesn't seem to be working as expected. I can click on each list item, but the active state is not being displayed correctly. Can someone please assist me with this issue? I w ...

OnPush strategy and template updates: Propagating modifications to the parent component

I am currently facing an issue with a parent component that consists of two templates. The first template simply displays data-bound text, while the second template contains a child component responsible for updating the data model. Both the parent and chi ...

Issues with message display validation in jQuery

Validation has been applied to the form, and there are div elements within the input fields with corresponding IDs. The goal is to display error messages within those divs. Specifically, if an input field is missing, the errorMessage should be set in the ...

Execute AJAX function following the completion of table loading from PHP in Ajax

I'm currently working on a shopping cart feature that involves calculating certain figures based on table values. The process involves loading the table using AJAX and PHP, which is functioning properly. However, I'm facing an issue where I nee ...

Step-by-step guide for setting up chartjs on Laravel 6 using npm

Can anyone guide me on how to properly install and integrate [email protected] in my laravel application? Currently, I am using cdn links, but I want to avoid that in the future. List of cdn links being used: <script src="https://cdnjs.c ...

npm fails during the build process due to webpack issues

I find myself lost in trying to pinpoint the right question to ask, but I am encountering a failure while running npm run build. > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="395a5655564b14564b5e585750435c4b790817091709" ...

Convert coordinates from X and Y within a rotated ImageOverlay to latitude and longitude

After going over all the details in Projection's documentation and conducting various trial and error tests, I have hit a roadblock in finding a solution to this particular issue. All the solutions I have come across assume the x and y coordinates ar ...