Break down an array-like object with no duplicates

I'm currently learning about working with JavaScript arrays and have a question regarding creating new array objects by splitting an attribute of an existing object.

I attempted using methods like .map and .flatMap, but the output I received consisted of duplicate object combinations, whereas my goal is to have unique objects.

Here's a more simplified version of the code:

const array=[ 
    { names:['something1', 'something2'],
      state:false,
      features:['feature1','feature2']
    },
    { names:['something3', 'something4'],
      state:true,
      features:['feature3','feature4']
    },
  ]

  array.flatMap(({names,state,features}) => {
    names.flatMap(name => {
      features.flatMap(feature => {
        console.log(({name,state,feature}));
      })
    })
  })

The current output from this code is:

{ name: 'something1', state: false, feature: 'feature1' }
{ name: 'something1', state: false, feature: 'feature2' }
{ name: 'something2', state: false, feature: 'feature1' }
{ name: 'something2', state: false, feature: 'feature2' }
{ name: 'something3', state: true, feature: 'feature3' }
{ name: 'something3', state: true, feature: 'feature4' }
{ name: 'something4', state: true, feature: 'feature3' }
{ name: 'something4', state: true, feature: 'feature4' }

However, my desired output should look like this:

{ name: 'something1', state: false, feature: 'feature1' },
{ name: 'something2', state: false, feature: 'feature2' },
{ name: 'something3', state: true, feature: 'feature3' },
{ name: 'something4', state: true, feature: 'feature4' }

I am relatively new to coding, so please forgive any inaccuracies in my explanation. Thank you for your understanding.

Answer №1

To map each element in the `names` array to its own respective object with its associated `feature`, you can utilize `.flatMap()` with an inner `.map()` function. This approach is more suitable than using multiple `.flatMap()` functions.

Check out this example:

const array = [{
    names: ['something1', 'something2'],
    state: false,
    features: ['feature1', 'feature2']
  },
  {
    names: ['something3', 'something4'],
    state: true,
    features: ['feature3', 'feature4']
  },
];

const res = array.flatMap(
  ({names, state, features}) => names.map((name, i) => ({name, state, feature: features[i]}))
);
console.log(res);

Answer №2

Here is a slightly edited version of the previous code snippet with name mapping:

const arr = [{
  names: ["test1", "test2"],
  values: ["t1", "t2"]
},
{
  names: ["test3", "test4"],
  values: ["t3", "t4"]
}];

const flat = arr.reduce((a, {names, values}) => {
   names.map((name, i) => {   
     a.push({ name, value: values[i]});
  });
  return a;
}, []).flat();

console.log(`Flat: ${JSON.stringify(flat)}`);

Answer №3

If you're looking to delve into the world of programming, using magic shortcuts may not always be the best approach. Concepts like map() and reduce() are algorithms in themselves. It's important to first master basic tasks using simple loops (for, while) and sometimes recursion (like finding the root cause of a particular issue).

If your data structure is an array with nested objects containing parallel arrays, you can iterate over them using both an outer loop for the main array and an inner loop for each nested object:

const array=[ 
    { names:['something1', 'something2'],
      state:false,
      features:['feature1','feature2']
    },
    { names:['something3', 'something4'],
      state:true,
      features:['feature3','feature4']
    },
  ];
  
for(let outer=0;outer<array.length;outer++){
  let obj=array[outer];
  for(let inner=0;inner<obj.names.length;inner++)
    console.log({
      name:obj.names[inner],
      state:obj.state,
      feature:obj.features[inner]
    });
}

While the outer loop doesn't necessarily require an index and could directly iterate over elements using for(let obj of array) or array.forEach(), the inner loop does need an index to properly traverse through the parallel arrays. This makes it slightly more complex than using functions like map(), as those tend to abstract away these details by presenting a clearer interface.

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

Warning: Unhandled promise rejection occurred while running the test

Currently delving into the world of selenium with a focus on testing the registration page. I've crafted a registration page class equipped with methods for monitoring registrations. However, upon attempting to execute a test within the application cl ...

A guide on showcasing nested arrays data in an Angular application

info = [ { list: [ { title: 'apple'} ] }, { list: [ { title: 'banana'} ] } ] My goal here is to extract the list items. Here is how they are structured. desired r ...

Perform an Ajax request to a PHP function using an array as the data payload within the WordPress platform

I have been struggling to send an array from jQuery to a PHP function and have tried various methods without success. I've experimented with $_request, $_post, using JSON.stringify, not using JSON.stringify, but all I get is 'null'. Can anyo ...

In Vue.js, it is not possible to modify a component variable within a callback function

I have implemented a custom Login.vue component using vue.js to allow users to log in to my application through AWS Cognito. The authentication process is handled by the ___.authenticateUser() method, which initiates a session with Cognito. Below is the co ...

Populate DataTables with data from JSON or JavaScript arrays and objects

Using jQuery(html), I was populating a table with data but now I am attempting to limit the displayed rows by switching the table to datatables. The data structure looks like this: dataArray = [{ id: 1, props: { abc: 123, def: 456 ...

The model in the Schema has not been registered, unlike other models from the same source that have been successfully registered

When populating a node express route with information from Schemas, I encountered an error that puzzles me. Even though I am referencing three different fields in the same Schema, I am only facing this error for one of those fields. The specific error mes ...

React Table component displaying data fetched from API is encountering errors when trying to access properties of null

While using React-Material-Table, I encountered an issue where some values are null, resulting in the error message "Uncaught TypeError: Cannot read properties of null (reading 'name')". 1. How can I address this problem? 2. Is there a way to se ...

Determining if an item is located within a nested scroll container

How can one detect if a specific element within a scrollable container is currently visible to the user's view (i.e. within the visible area of the scrolling parent)? Is there a universal method available that does not require iterating through all p ...

What is the best approach for encoding text inputs automatically?

In order to prevent my application from crashing due to the error "A potentially dangerous Request.Form value was detected...", I initially disabled page validation. However, I am now reassessing this approach and aiming to resolve it properly. Is there a ...

Firefoxx effortlessly glides divs across the screen as if they were images

Below is the HTML, CSS, and JavaScript code all in one document for testing: <style type="text/css"> #slider_container { width: 200px; height: 30px; background-color: red; display:block; } #slider { width: 20px; height: 30px ...

What are the steps for enlarging the display containing components with the 'position: absolute' style?

How can I magnify the screen with the following code? .drawing-board { width: 25%; height: 25%; background-color: black; position: relative; /* transform: scale(2, 2); */ } .drawing-board .box-1 { width: 20px; height: 20px; background-c ...

What is the best way to convert a flatTreeNode into a populated tree structure

Is there a way to structure a treeFlatNode array into a tree format in Angular, or display the array directly as a tree? data=[ { expandable: true level: 0 name: "2021-12-31" path: null }, { expandable: false level: 2 ...

Tips for submitting multiple radio button values in a tabular format

HTML Code: <div class="tab"><h4>Zip Code</h4> <p><input type="text" class="text1" placeholder="Enter zip code..." oninput="this.className = ''" name="zipcode"></p> </div> <div class="tab">& ...

Retrieve a byte array byte[] from a JSON object in a Java Android application

I am working on a Json post service that requires passing 2 integer parameters. Here is the code snippet: obj.put("id", par); obj.put("type", par2); After passing the parameters, I can see the following response from the service using Fiddler2: {"Ge ...

Implementing a Toggle Class Feature in a Function

I am currently facing an issue with a function that triggers an overlay on mouseenter event and needs to be unbound. I want to incorporate a way to close the overlay with a specific 'x' element and allow the user to trigger the event again. Howev ...

Tips for verifying whether a variable is a node?

Curiosity strikes me: how can I determine if the variable myVar is a node? I could simply check myVar.nodeType, but that might be misleading with something like {nodeType:1} So, naturally, I start to wonder if there's a way to do this instead: myVa ...

Pressing a key will initiate a time delay before

I have a coding challenge where I need to navigate through a sprite sheet using setTimeouts. Everything is functioning as expected, but I am curious about implementing a feature that allows me to skip frames by pressing the "m" key. Essentially, I want it ...

Error encountered: "Cannot execute babel using npm script because the command was not found"

To begin, I initiated the following commands: npm install --save-dev babel-cli npm install --save-dev babel-preset-es2015 npm install --save-dev babel-preset-stage-0 This is the content of my package.json: { "scripts": { "build": "babel ...

The functionality of Directive hinges on the use of a template

I am exploring a more web-component approach to using Angular. As part of this, I have developed an http-request directive with url and response attributes. The implementation is successful, but I find that my directive relies on a template unnecessarily. ...

What is the most efficient way to calculate the total sum of all product amounts without using Jquery?

I am working with a dynamic table where data is inserted and the total of each product is calculated by multiplying the price by the quantity. What I need now is to get the sum of all the totals for each product. You can see how the table looks here: htt ...