An alternative solution for flatmap in JavaScript

Searching for a workaround for flat map not working on IE led me to this solution, but the reasoning behind it eludes me.

var gadjets = [
  {computers:['asus', 'hp'],
  sellphones:['Galaxy', 'Nokia']
  },

  {computers:['dell', 'insys'],
  sellphones:['iphone', 'samsung']
  }
];

const getValues = gadjets.reduce((acc, gadjet) => acc.concat(gadjet[computers]), []) // instead of gadjets.flatMap(gadjet=> gadjet[computers])

The output of this code snippet is:

['asus','hp','dell','insys']

But shouldn't it actually return:

['asus','hp'],['dell', 'insys']

Answer №1

The reason for this behavior is that the reduce function in JavaScript accumulates or adds up the values provided to it. To illustrate, consider the following code snippet:

let numbers = [1, 2, 3, 4, 5];
console.log(numbers.reduce((total, num) => total + num));

In this example, each number is added to the running total, which is then passed on as a new total to the next iteration of the reduce function.

What you were doing in your code was passing an entire array into the accumulation process through acc, and then concatenating a new array using elements from gadgets['computers']. This effectively creates a combined list of computer items from an array of objects.

For more detailed information about the reduce method, you can refer to the documentation here.

Answer №2

However, shouldn't the outcome be different

I am uncertain about what you are attempting to demonstrate, but if you are referring to the following:

[['asus','hp'],['dell', 'insys']]

In that case, the result should not be like that. concat merges the arrays you provide into a single level:

const a = [].concat(['asus','hp'], ['dell', 'insys']);
console.log(a); // ["asus", "hp", "dell", "insys"]

Thus, acc.concat(gadjet[computers]) combines all the computers arrays into one new array, which is the accumulation result of the reduce.

Answer №3

If you're looking to get the output as an array of arrays, give this a try:

var electronics = [
  { laptops: ["MacBook", "Dell"], smartphones: ["iPhone", "Samsung"] },
  { laptops: ["HP", "Lenovo"], smartphones: ["Google Pixel", "OnePlus"] }
];
const groupItemsBy = key => {
  let result = electronics.reduce((objectsByKeyValue, obj) => {
               let arr = [];
               arr.push(obj[key]);
               return objectsByKeyValue.concat(arr);
        }, []);
   return result;
};
console.log(groupItemsBy("laptops"));

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

Utilizing a JavaScript function to toggle the Bootstrap dropdown without the need for manual clicking

I've configured a Bootstrap dropdown in my site's mini cart that includes a lightbox effect to grey out the background content when the dropdown is activated. Here's the code snippet: $(".dropdown").on('show.bs.dropdown hide.bs.dropdow ...

Using @click within a Vue.js component does not trigger any response or action

<template> <div class="container" id="app"> <button @click="console.log('hello')"> Hello </button> </div> </template> <script> export default { name:"test", } </script> ...

Transmitting information through ajax and fetching it using Request.Form[""]

My struggle lies in passing parameters from a js script to an aspx.cs page. Interestingly, when I exclude the following line: contentType: "application/json; charset=utf-8" from my ajax request, the data received by Request.Form["ORDER"] appears as {%7b% ...

Adding a namespace in a .js file

In the MVC application I'm developing, all JavaScript for the pages is stored in separate JavaScript files without any script tags on the pages. There's a Messages class containing Errors, Information, and Confirmation classes with static strings ...

Initiating a GET request to retrieve the file generated by the server

I am currently delving into the Mean stack and have encountered a challenge with downloading a file from my server-side application using the Angular front end. Despite successfully generating the file on the back end, clicking the download button on the f ...

What sets apart .andReturn(...) from .respondWith(...) when running AJAX call tests in JavaScript using Jasmine?

While utilizing the jasmine-ajax library for testing JavaScript code, I have discovered a way to mock ajax responses. There are essentially two methods to achieve this: Method #1: jasmine.Ajax.requests.mostRecent().respondWith({ status: 200, contentT ...

Exploring promises with loops and patience?

I created a function that accesses an API and retrieves an array containing 100 objects at once. The getPageData() function works as expected when passing an integer without the loop. However, when attempting to iterate through it, I am not getting any res ...

Finding the main page URL using PHP within a JavaScript include: A comprehensive guide

I am facing an issue where I have a page with a header include that needs the phone number to change only if the filename of the current page contains a specific word. Typically, for a change outside of an include, the following code would suffice. <? ...

Troubleshooting issues with JSON data in d3 Sankey charts

I seem to be encountering an issue with creating a graph and could really use some assistance. I am attempting to create the following chart: http://bl.ocks.org/wvengen/cab9b01816490edb7083 However, every time I try, an error occurs and causes the browser ...

Issue with accessing Vue.js parameter in route

Trying to work with both VueJS and Laravel, I am currently facing an issue where I cannot retrieve a parameter value. Can anyone provide guidance on how to solve this problem? This is my VueJS code: getTestData:function () { let config = { par ...

Optimal method of creating and initializing store items in Vue using Vuex

As a newcomer to Vue, I am exploring the best approach to manipulate a "master" store object by stripping keys, renaming others, and creating an altered version to save as a new store item. In my App.js file, I initiate a "loadData" action within the crea ...

problem with increasing/decreasing buttons in a react application

My goal is to display a list of Names in a specific order, but I'm encountering an issue when using the increment and decrement buttons. When I click the increment button, the order increases by 1 as expected. However, when I click the decrement butto ...

The array containing prime numbers fails to display its contents accurately

Having encountered some challenges with an array in Java, my goal was to utilize threads to store prime numbers in an array. Despite my efforts, it seems that the implementation is not working as expected. The objective here is for b[c] to contain all prim ...

Switch the minimum value in a NumPy array with a different value

Assume we are working with an array and need to replace the smallest value with 50 import numpy as np numbers = np.arange(20) numbers[numbers.min()] = 50 The resulting array is [50,1,2,3,....20] However, when attempting this: numbers = np.arange(20).re ...

Modifying a variable in $rootScope data will also update other instances of $rootScope data

Since I need to use the data in multiple controllers, I have stored it in $rootScope.currentCache. When the page loads, the data typically looks like this: { System: "Foo Bar", StartDateTime: "2014-11-27T12:35:00" } (please disregard any formatti ...

What is the method for ensuring that a GreaseMonkey script impacts elements on a page prior to their appearance?

I'm currently working on a project that requires hiding images on a specific website while still displaying the alt text. Initially, I tried to achieve this using Stylish on Firefox and posted the following question: How to force an image's alt ...

Guide on transferring value from a <select> element using JavaScript

I'm attempting to pass the selected value of a <select> in the onChange function. I've explored this question on SO, but unfortunately, using this and this.value hasn't been successful. I understand that the question is quite old... se ...

Switch up the side navigation panel display

Hello, I am a newcomer to bootstrap and I have successfully implemented a collapsing navbar. However, I am looking for a way to make the navbar slide out from the right side when clicked on in mobile view. Can someone provide me with some JavaScript or j ...

What is the best method for aggregating multiple JSON responses into a single array?

I am struggling to get my data in the desired format of [{..},{..},{..}]. I have created an empty array using const arr = [], but when I push all JSON data into this array, the output shows as separate arrays. How can I fix this issue? // const arr = [] co ...

Setting up a software from a GitHub source

My issue arises when attempting to install a particular package of mine with the version specified as a specific git branch. The problem occurs because the repository does not contain the dist folder, which is required by my npm package. Here is the metho ...