Organize objects within an array based on their properties using a map function

My JavaScript code includes an array of objects structured as follows:

const selection = [
        {id: 'P282', areas: ['188']},
        {id: 'P277', areas: []},
        {id: 'P280'},
        {id: 'P281'},
        {id: 'P279'},
        {id: 'U57', areas: ['190', '189', '188']},
      ];

I aim to extract all the areas from each user and store them in a separate array that looks like this:

const extractedAreas = ['188', '190', '189', '188']

This new array may include duplicate elements if present.

Answer №1

If you want to extract zones from an array, one way to do it is by using the array.reduce() method.

const fetchZones = (arr) => {
    return arr.reduce((accumulator, current) => {
        if (current.zones) {
            return [...accumulator, ...current.zones];
        }
        return accumulator;
    }, []);
}

Answer №2

Array.reduce offers the optimal solution for your scenario.

const array = [{
    userId: 'P282',
    zones: ['188']
  },
  {
    userId: 'P277',
    zones: []
  },
  {
    userId: 'P280'
  },
  {
    userId: 'P281'
  },
  {
    userId: 'P279'
  },
  {
    userId: 'U57',
    zones: ['190', '189', '188']
  },
];

const result = array.reduce((acc, item) => {
   return acc.concat(item.zones ?? []);
}, []);

console.log(result);

Answer №3

When you are in the process of learning, it is recommended to implement a straightforward use of the for loop. By utilizing the spread operator (...), you have the ability to disassemble an array into its individual components.

You can achieve optimal results by combining both techniques to obtain the desired zones:

const array = [
        {userId: 'P282', zones: ['188']},
        {userId: 'P277', zones: []},
        {userId: 'P280'},
        {userId: 'P281'},
        {userId: 'P279'},
        {userId: 'U57', zones: ['190', '189', '188']},
      ];
      
      let zones = [];
      for(let i = 0 ; i < array.length;i++){
      if(Array.isArray(array[i].zones))
      zones = [...zones,...array[i].zones];
      
      }
      
      console.log(zones);

Answer №4

  • flatMap retrieve zones and place them in a single array.
  • Eliminate any instances of undefined by using filter(Boolean)
array.flatMap(x=>x.zones) // ['188', undefined, undefined, undefined, '190', '189', '188']
.filter(Boolean); // ['188', '190', '189', '188']

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

If an element exists in one of the dimensions of a multi-dimensional array

I am facing an issue with my 2D array structure. Here is an example of how it looks: `var arr = [["1", "2", "3"], ["4", "5"], ["6"]];' Despite having the value "4" in one of the inner arrays, when I try running $.inArray("4", arr); or arr.indexOf("4" ...

Unable to get PHP session to function properly in Aurelia framework

I am currently utilizing Aurelia framework along with PHP as the backend. Below is the code snippet of my view and its corresponding model: home.html <template> <require from="datepicker.js"></require> <form submit.delegate=" ...

Disabling the loading of JavaScript on a Magento website

Seeking advice - I'm experiencing a delay on my website due to 3 unnecessary javascripts that are being loaded. Is there a way to prevent these scripts from loading or being searched for? Listed below is the website log where I am unable to locate jq ...

Issues with JavaScript's getTime() function I am facing problems with

Currently, I'm developing a simple HTML quiz consisting of 10 questions, each on a separate HTML page. Upon the user clicking the START button on the index.html page, the following script is triggered: var s = new Date(); sessionStorage.start_test = ...

Attempting to alert a particular device using Flutter for notification delivery

Currently, I am developing a Chat app using Flutter and attempting to send notifications to specific devices through Firebase functions. Initially, I retrieve the device token and store it in Firebase. Now, my challenge lies in fetching the token and invok ...

A program designed to access and retrieve a universal variable

It seems like a simple task, but I can't seem to figure it out. I'm trying to assign the currentUserId within the getCurrentUser function so that I can use it in other functions. Currently, the code below is returning undefined. What am I overl ...

There is an issue showing up in the console: $(…).datepicker is not defined as a function

I am new to using HTML with JavaScript. I attempted to implement a datepicker, but unfortunately, it is not working as expected. The error message I am receiving is '$(...).datepicker is not a function' in the console. I am utilizing multiple f ...

Is Jquery "resistant" to updating CSS properties?

Within my HTML document, there exists a div with the class fd-video-upload-box, which has the following style properties applied: background-color: rgb(236, 238, 239); outline: 1px dashed gray !important; Upon rendering, it displays correctly as intended ...

Ending asynchronous tasks running concurrently

Currently, I am attempting to iterate through an array of objects using a foreach loop. For each object, I would like to invoke a function that makes a request to fetch a file and then unzips it with zlib, but this needs to be done one at a time due to the ...

How can you incorporate a custom button into the controlBar on videoJS in responsive mode?

The video player I have created using videoJS includes custom buttons in the control bar. These buttons are not clickable when viewed on mobile or tablet devices without forcing them to work. let myButton = player?.controlBar.addChild('button'); ...

I'm trying to access my navigation bar, but for some reason, it's not allowing me to do so

Having trouble getting the navigation bar to open. I have set it up so that when clicked, it should remove the hide-links tag, but for some reason, it does not toggle properly and keeps the ul hidden. import React from "react"; import { NavLink } ...

Converting Arrays into Objects with Multiple Dimensions

I have been attempting to transform this complex array into an object. However, I am facing an issue where only the second part of the array is being saved in the object, while the first part is missing. Is there a way to ensure that the entire array gets ...

Transferring array data into a table

I need assistance organizing an array into a table format with a new column after a certain number of items. Here is an example: item 1 | item 2 | item 3 | item 4 | item 5 | item 6 | item 7 | item 8 | item 9 | and so on... I have managed to add a new c ...

I am interested in incorporating jQuery into my React development project

I'm trying to implement jQuery in React. I have an input field in my project that I am using to create a match event with 'this.state.value'. When the content of the input field matches, I want the borders to turn green and red if they do no ...

Is there a way to implement an X icon in Material UI Modals to close them instead of relying on clicking outside the modal?

In my React app, I am utilizing the Material UI Modal component which occupies around 95% of the screen. To improve user experience, I want to include a small "X" icon in the upper right corner of the modal for closing it. Although I am passing down the sa ...

Why is it that when I add a set of markers from an array list, only the final value is displayed?

Struggling with adding markers to Google Maps using an array list - it only shows the last value from the array. Can anyone help me figure this out? Here's the loop I'm working with: for(int k=0;k<jsonarray2.length();k++) { jsonobject2 =j ...

Tips on hiding specific table rows in two separate tables based on the chosen option from a dropdown menu

How do I hide table rows based on dropdown selection? The first table has a dropdown with two options: Current State and Future State. If I select Current State, I want to show or hide specific rows in the 2nd and 3rd tables. I am using IDs for these row ...

React web app experiencing an issue with MUI Drawer opening flawlessly but failing to close

Recently, I encountered an issue with my React app. I have a Navbar component that displays a Sidebar component when the screen is small, using Material UI for the Drawer functionality. The problem arises when clicking the hamburger icon to open the drawe ...

What is the reason for allowing a char pointer variable to be initialized with a string, while disallowing an int pointer variable to be initialized with an array of integers

I am exploring the connection between strings, arrays, and pointers. In a book I'm studying, there's a program where a variable is set up like this: char* szString= "Name"; From what I grasp, a C-style string is essentially an array of charact ...

The html-duration-picker is not being displayed in the proper format

I've been working on integrating an external library that allows for inputting document length. Specifically, I'm using the html-duration-picker library, but it seems like the input functionality is not quite right for durations. Could it be th ...