Mastering the functionality of array.map()

Apologies for the simplicity of my query.

I am in the process of streamlining some code and have been exploring the use of array.map rather than traditional for loops to iterate through arrays and using array.push. I've managed to grasp the fundamentals, but I'm facing difficulties when trying to add a conditional statement. Here is my current code snippet:

var masterArray = [{
    "masterName": "One",
    "minorArray": []
  },
  {
    "masterName": "Two",
    "minorArray": ["A", "B", "C"]
  },
  {
    "masterName": "Three",
    "minorArray": ["Q", "W", "E", "R", "T", "Y"]
  },
  {
    "masterName": "Four",
    "minorArray": [1, 2, 3, 4, 5]
  },


];
var minorArray = [];

var setMinorArray = function(value) {
  var selectedName = value;

  for (var i = 0; i < masterArray.length; i++) {
    if (masterArray[i].masterName == selectedName) {
      minorArray = [];
      minorArray = masterArray[i].minorArray;
      break;
    }
  }

  console.log(minorArray);
};

setMinorArray("Three");

Since I need compatibility with IE11 users, I am unable to utilize arrow functions. Any guidance on this would be greatly appreciated.

Thank you so much

Answer №1

map isn't the best choice here - you should be using find to locate an element in the array:

var masterArray = [{
    "masterName": "One",
    "minorArray": []
  },
  {
    "masterName": "Two",
    "minorArray": ["A", "B", "C"]
  },
  {
    "masterName": "Three",
    "minorArray": ["Q", "W", "E", "R", "T", "Y"]
  },
  {
    "masterName": "Four",
    "minorArray": [1, 2, 3, 4, 5]
  },


];
var setMinorArray = function(value) {
  var minorArray = masterArray.find(x => x.masterName === value).minorArray;

  console.log(minorArray);
};

setMinorArray("Three");

Answer №2

Using the map() function in this scenario would not be appropriate. The ideal use case for map() is to create a new array containing processed elements from the original array. However, in your loop, the condition is checked before processing each element, and the loop exits after processing that element.

Instead, you should consider utilizing the find() function. This method returns the first element that satisfies a specific condition.

var masterArray = [{
    "masterName": "One",
    "minorArray": []
  },
  {
    "masterName": "Two",
    "minorArray": ["A", "B", "C"]
  },
  {
    "masterName": "Three",
    "minorArray": ["Q", "W", "E", "R", "T", "Y"]
  },
  {
    "masterName": "Four",
    "minorArray": [1, 2, 3, 4, 5]
  },
];
var minorArray = [];

var setMinorArray = function(value) {
  var found = masterArray.find(({masterName}) => masterName == value);
  if (found) {
    minorArray = found.minorArray;
  }
  console.log(minorArray);
};

setMinorArray("Three");

Answer №3

While Array.map may not be the ideal tool for this task, it can still be used in a creative way if necessary:


const mainArray = [
  { mainName: 'One', subArray: [] },
  { mainName: 'Two', subArray: ['A', 'B', 'C'] },
  { mainName: 'Three', subArray: ['Q', 'W', 'E', 'R', 'T', 'Y'] },
  { mainName: 'Four', subArray: [1, 2, 3, 4, 5] },
]

const selectedValues = ['Three', 'Two']

const subItems = mainArray
  .map(({ mainName, subArray: sa }) => selectedValues.includes(mainName) ? sa : [] )
  .join(',')
  .split(',')
  .filter(item => !!item)

console.info({ subItems }) // output will be ["A", "B", "C", "Q", "W", "E", "R", "T", "Y"]

Answer №4

You can easily transform the array into a key-value lookup object using the reduce method, which has been supported since IE 9:

var mainArray = [ { "mainName": "One", "subArray": [] },
                    { "mainName": "Two", "subArray": ["A", "B", "C"] },
                    { "mainName": "Three", "subArray": ["Q", "W", "E", "R", "T", "Y"] },
                    { "mainName": "Four", "subArray": [1, 2, 3, 4, 5] } ];

var keyValueObj = mainArray.reduce(function(obj, item) { 
                               return (obj[item.mainName] = item.subArray, obj); }, {});

console.log( keyValueObj["Three"] );

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

"Splitting a DOMNodeList into an array of chunks using PHP

I am attempting to utilize an array chunk function with a DOMNodeList. Unfortunately, this is resulting in an error message as the DOMNodeList does not conform to the standard PHP array format. Below is the code snippet causing the issue: foreach (array_c ...

Restrict HTML Content in Json Result using PHP and Jquery

I'm currently working with a Controller that outputs JSON response and a JavaScript function that appends that response to the last tr in an HTML table. <pre> $reponse="<tr class=\"border_bottom\"><td>My Repo ...

Encountering a 500 (Internal Server Error) while trying to insert data into the database through ajax

In the HTML code, I have a basic AJAX function that is triggered by a button press. The goal is to have the PHP script being called insert the JavaScript variable sent into a database. var myval = 'testuser'; // generated by PHP $.a ...

Set a value within a string array as the string property for each item in an array of custom objects

Let's imagine I am dealing with an array of countries' names stored in a variable called countryNames[]: string[] countryNames = { "Afghanistan" , "Albania" , "Algeria", ... } Moreover, there exists a class named Country which contains various ...

Exploring the functionalities of radio buttons and arrays in a Javascript experiment

Currently delving into the world of Javascript and struggling to wrap my head around creating a test using only pure Javascript (no jQuery). The goal is to: Present users with a question and provide radio button options for selection. Allow users to cho ...

Embed message from a Discord Bot

Is it possible to include an image of a bot on the right side of the embedded message? if (message.includes('help')) { msg.channel.send({ embed: { title: "xxxxxx", color: 3447003, description:"Enter **agjgj** to know ...

Azure Function App experiencing unexpected delay in async operations

I'm currently working with the Azure storage SDK for node in order to create a Table in Table Store if it doesn't already exist. After running the following code, I receive a 200 response with no content. However, the table is successfully creat ...

Encountering JSON parsing errors while using fetch() POST requests in Express

Currently, I am experimenting with HTTP requests and my main focus is on sending a POST request. The data for this request is coming from an input field and I am using fetch() to send it to a URL on my local host which is set up with express. My goal is to ...

I am looking to display the pop-up exclusively when the page is clicked, but unfortunately it is also appearing when the Menu is clicked

I've been working on this code and trying to make some modifications, but I just can't seem to find the right solution for my issue <!-- Updated main content --> <main> <p> Click on the menu button located in the top right ...

Showcasing text behind an element with reduced opacity when the element directly above it is selected using rails, CSS, and jQuery

I have a password field on my page where the password is hidden, but I want users to be able to copy and paste the clear text version of the password on another website. In order to achieve this, I followed the instructions in an article titled Mask text, ...

Limit the picture file size to 20 kilobytes with jQuery on the front end

Currently, I am using PHP to handle post submissions, but I am facing a challenge. I need to limit the size of image uploads to 20kb before the form is submitted. My scenario involves uploading three images individually in different fields. Any assistance ...

Utilizing AngualarJS to bind data to intricate objects using the $resource functionality

Currently, I am working on a restful service that retrieves an order along with a list of items. In my project, I am developing a screen where users can edit specific items within the order. To achieve this, I need to display the list of items before locat ...

Incorporate a Google Chart link by integrating it with a select handler

I'm facing an issue while trying to open a link in a Google line chart using the selection handler. The chart stops rendering, and as a newcomer to javascript, I'm unsure why. This is how the code is integrated into my HTML: <pre><code ...

Progressive reloading page with Jquery Ajax upload

I've encountered a strange issue with a Jquery form submit. After the upload completes, the page reloads even though the server hasn't finished processing. The server only returns a JSON success status, so it's not an issue on the server s ...

Bringing in Vue from 'vue' allows for the incorporation of 'different' Vue to diverse documents

This issue involves the interaction between Webpack, ES6 import syntax, and Vue. Currently, I am working on a Vuex mutation that is responsible for adding a new key-value pair mykey: [] to an object within the state. To ensure reactivity, I need to use Vu ...

Parsing JSON data as files are being read in an asynchronous manner

I have a task of reading multiple JSON files and consolidating their data into a single array. Here is my approach: const files = ['file0.json', 'file1.json', 'file2.json', 'file3.json'] To achieve this, I utilize ...

Ways to retrieve information from a intricate JSON structure?

Can anyone help me understand why I am unable to access the data in the detail option of the JSON? My goal is to load the firstName, lastName, and age into a list for each object. var data = { "events": [{ "date": "one", "event": "", "info ...

Submit simple text via XMLHttpRequest to an Express server

I am currently facing an issue with making a post XMLHttpRequest to my Express server. Despite attempting to send a string, it seems that I am missing something crucial in my implementation. Client: const sendMessage = () => { const message = "This ...

Issues with the Winston transport for Loggly are causing inconsistent performance

I have implemented Winston with 3 transports: Console, File, and Loggly (using https://github.com/loggly/winston-loggly-bulk). While the Console and File transports are functioning properly, I am facing an issue with the Loggly transport. It only logs my ...

Tips for safely executing an SQL query with electron.js

I have a new project where I need to interact with an SQL database on the local network, but it's not located on the same system I'm working on (not SQLExpress). So far, I've figured out how to collect user input on a webpage and send that ...