The ES6 reduce method is not giving the expected result

In Image 1, the output you will see if you log the final array from Snippet 1.

My goal is to transform my array to match the format shown in Image 2.

I attempted using lodash's _.uniqBy() method [Snippet 2], but the logged output of the reduce variable still resembles Image 1. How can I modify my final array to resemble the desired output in Image 2?

https://i.sstatic.net/TiYHw.png Image 1

https://i.sstatic.net/rZ8WA.png

Image 2

const reduce = final.reduce((x, y) => {
  if (x.department !== y.department) {
    return x;
  }
})

console.log(final)
console.log(reduce);

Snippet 1

_.uniqBy(final, 'department')

Snippet 2

UPDATE

This scenario pertains to TypeScript (.ts) rather than JavaScript (.js).

Data Structure =>

[{ department: string, professors: string[] }]

Regarding the request

The source of my data is specified here

[
    {
      department: 'Department of Mathematics - INTRAMUROS',
      professors: [
        'Sabino, Lilibeth D.',
        'Department Chair',
 .....

Below is an excerpt of my code before arriving at the final array:

const recommend = [];
const final = [];

recommended.forEach((prof) => {
  const find = proffessorDetails.find((collection) => {
    return collection.professors.find((professor) => professor == prof);
  });
  recommend.push(find);
})

const find = recommend.map((collection) => {
  return {
    department: collection.department,
    prof: _.intersection(collection.professors, recommended)
  };
});
final.push(find);

Answer №1

Opting for a Map would be the ideal choice in this scenario:

type section = { division: string, teachers: string[] };
let uniqueMap : Map<string, section> = new Map(data.map((item: section) => <[string, section]>[item.division, item]));
let uniqueArray = [...uniqueMap.values()]; //or Array.from(uniqueMap.values());

Answer №2

By using the reduce method, you can efficiently modify and return the same object. It is recommended to start with an initial value (such as {}). This acts as your base object (obj) throughout the process. To store unique values for each item, simply assign them to obj[item.department]. Remember to include a return statement for the object at the end.

const reduce = Object.values(final.reduce((obj, item) => {
  obj[item.department] = item;
  return obj;
}, {}));

When utilizing Object.values, you can extract only the values from the reduced object.

Answer №3

To clarify, it is necessary to pass the accumulator as the first argument to the reduce callback function. For more information, please refer to this link: Array.prototype.reduce. It's not guaranteed that this is the solution you are seeking, but the following code will result in an array containing objects with a unique department field.

final.reduce((res, item ) => {
    return res.find(({ departament }) => departament === item.departament) ? res : [res, item];
}, [])

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

Movement and physics mechanics for players using Physi.js

As I work on a basic game using Three.js for rendering and Physijis for physics, my question can be applied to games in general. In games, players often display movement that appears disconnected from the physics engine. They can accelerate instantly and ...

Switching from using fs.readFile to fs.createReadStream in Node.js

I have a dilemma regarding my code, which involves reading an image from a directory and sending it to index.html. My goal is to replace fs.readFile with fs.createReadStream, but I am struggling to figure out how to implement this change as I cannot seem ...

What is the process of extending a class in TypeScript?

I have a few services that contain the same code: constructor (private http: Http) { //use XHR object let _build = (<any> http)._backend._browserXHR.build; (<any> http)._backend._browserXHR.build = () => { let _xhr = _ ...

Exploring various layers of nested data

I am currently developing a comprehensive global data storage system for my application (specifically an Angular JS app - although this question pertains to JavaScript in general). I have established a 'service' that is responsible for setting t ...

Generate a dot density map with the help of Google Maps

I am looking to create a dot density map using Google Maps for my state. I have all the counties outlined with their respective populations, and I want to scatter dots randomly within each county to represent the population. The goal is to make a dot densi ...

What is the best approach for resolving this asynchronous task sequencing issue in JavaScript?

Below is a code snippet where tasks are defined as an object and the function definition should ensure the expected output is met. Let tasks = { ‘a’: { job: function(finish){ setTimeout(() => { ...

How can you prevent the keys from being read-only when mapping onto a type?

Here's a common query: How can I change keys from readonly to writable when using a type that is Readonly? For example: type Foo = Readonly<{ foo: number bar: number }> type Bar = /* What's the method to duplicate the Foo type, but w ...

Next.js API is throwing a TypeError because req.formData is not a recognized function

Below is the code snippet for the Next.js route I am working on: import { NextRequest, NextResponse } from 'next/server'; export const config = { runtime: 'edge', }; export default async function POST(req: NextRequest): Promise< ...

Customizing event colors in Full Calendar

My interactive calendar is created using : $('#calendar').fullCalendar({ height: 300, //............. events: jsonData, month: firstMonth }) I am looking to dynamically change the color of an event based on certain conditions ...

Verify the input in text fields and checkboxes using JavaScript

I'm in the process of creating a complete "validate-form" function, but there are still a couple of things missing: Ensuring that the Name field only allows alphabetical characters and white spaces Validating that at least one checkbox is selected, ...

Get Subject Alternative Name from X.509 in a Node.js environment

Having trouble retrieving the SAN from a DoD Smart Card, as the subject alternative name is returning othername:<unsupported>. I have not been able to find many examples on how to parse this information. I would have thought that X509 li in node woul ...

POST request in Ajax with NodeJs/MongoDB/Mongoose causing an Uncaught TypeError: Illegal invocation

Whenever I attempt to make a POST request using Ajax/Jquery, I keep encountering an error in the console. The specific errors are on lines 67 and 31 in the createTeam.js file: $.ajax({ //line 67 sendInvitation(teamID,_companyName,teamName) //lin ...

When I click a button in d3 to refresh the data on my bar graph, the text fails to update accordingly

I've successfully created a series of data lists that modify the bargraph. Unfortunately, due to their differing x and y values, they end up printing new values on top of existing ones. Shown below is an image illustrating the issue where x and y val ...

What could be causing my component to not refresh when used as a child?

I have been experimenting with some code to track rerenders. The initial approach failed when passing <MyComponent> as a child component. it("should return the same object after parent component rerenders", async () => { jest.useF ...

Setting up OpenID configuration in angular-oauth2-oidc to bypass authentication for certain addresses

In my Angular project, I implemented OpenID authentication using the angular-oauth2-oidc project. However, I need to disable authentication for certain routes. To achieve this, I start the code flow in the main component and bootstrap it in the main modu ...

What is the best way to create a menu in JavaScript that includes a variable declaration?

Here is the menu I've created: <a id="page1" href="" onclick="var = page1">Home</a> <a id="page2" href="" >About us</a> <a id="page3" href="" >Services</a> <a id="page4" href="" >Partners</a> <a ...

The sequence for initializing properties in Typescript

In my Typescript code, I have 2 classes named A and B. Class B inherits from class A, where class A's constructor calls a function called init, and class B overrides the init function. a.ts export default class A { constructor() { this.ini ...

Retrieve the value of the object within the mysterious index loop in JavaScript

I have retrieved search results from the data, and each time the index of my search result varies. At one point, the result may appear in the 4th index, while at another time it might be in the 100th index. How can I retrieve the rank value from within t ...

The error message "MongoDB - MongoError: connect ECONNREFUSED" indicates a

I am encountering an error every time I attempt to connect to mongoDB. Despite looking through various similar questions, I have yet to find a solution for my specific issue. Here is the exact error message: connection error: { MongoError: connect ECONNR ...

Encountering difficulties in creating an app with Apache Cordova

After setting up the proxy settings, I attempted to create a new app named "hello" using Cordova with the following commands: npm config set proxy http://proxy.company.com:8080 npm config set https-proxy http://proxy.company.com:8080 The creation comman ...