Innovative manipulation of arrays using Javascript

Let's say I have some sample input data:

data = [
  { color : 'Red', number : 5},
  { color : 'Blue', number : 3 },
  { color : 'Green', age : 8 },
  { color : 'Red', number : 7 }
]

and I am looking to combine and transform this data into the following format:

result = [
  { number : 3, color : ['Blue'] },
  { number : 5, color : ['Red'] },
  { number : 7, color : ['Red'] }, 
  { age : 8, color : ['Green'] } 
]

I want to find a solution that is flexible and dynamic without specifying key or value names. Thank you!

Answer №1

Feel free to give this code a chance:

let info = [
  { title : 'Emma', age : 24},
  { title : 'Frank', age : 22 },
  { title : 'Lily', age : 25 },
  { title : 'Sam', age : 22}
]
let result = []
info.map(record => {
  obj = result.find(item => item.age === record.age )
  if (obj) obj.title.push(record.title)
  else result.push({age: record.age, title: [record.title]})
})

console.log(result)

Answer №2

Check out this example that demonstrates how you can iterate, map, and manipulate data sets to group them as needed:

https://jsfiddle.net/8c3xm2vl/

const data = [
  { name : 'Alice', age : 21},
  { name : 'Henry', age : 20 },
  { name : 'Max', age : 20 },
  { name : 'Jane', age : 21}
];

const mapping = new Map();

for (let i = 0; i < data.length; i++) {
    const element = data[i];
  for (const prop in element) {
    const key = prop + "" + element[prop];
    if (mapping.get(key) != null && mapping.get(key).val === element[prop]) {
        const matches = mapping.get(key);
      matches.list.push(element);
    } else {
        const matches = {val: element[prop], key: prop, list: [element]};
      mapping.set(key, matches);
    }
  }
}

let result = [];
mapping.forEach((val, key) => {
    if (val.list.length > 1) {
    let res = { matches: val.list };
    res[val.key] = val.val;
    result.push(res);
  }
});

console.log(result);

Result:

0:
age: 21
matches: Array(2)
0: {name: "Alice", age: 21}
1: {name: "Jane", age: 21}
1:
age: 20
matches: Array(2)
0: {name: "Henry", age: 20}
1: {name: "Max", age: 20}

I chose not to display single-element groupings and left the value manipulation up to you. Use this code snippet as a foundation for creating the desired data structure. For further assistance, provide more context on your goal. Best of luck!

Answer №3

Let's dive into the trick and get our hands dirty. This roadmap isn't a direct solution, but once you understand it, you can narrow it down to a function that suits your specific needs.

    data = [
  { name : 'Alice', age : 21},
  { name : 'Henry', age : 20 },
  { name : 'Max', age : 20 },
  { name : 'Jane', age : 21}
]

Now, we need to search and reduce the given set of unique age values through loops. We declare a set of variables to work with:

var a = [];
var c= [];
var i;
var ii;

var iii; var iv;
Next, let's loop through the entire process:

for (i = 0; i < data.length; i++) {

  a.push(data[i].age)
 
}
 a=[...new Set(a)];

This provides us with unique age values as an array from the data array. One problem solved. Now, we create a placeholder array from the newly generated unique array:

for (ii = 0; ii < a.length; ii++) {

  c.push({'age':a[ii], 'name':[]})
} 

With placeholders set according to the unique array, we search and match from the data array and populate the name array in the placeholder array:

for (iii = 0; iii < c.length; iii++) {
for (iv = 0; iv < data.length; iv++) {
if(data[iv].age == c[iii].age){c[iii].name.push(data[iv].name)}
}
}

It's as simple as that. You can create multiple functions to make it more organized, but this is the basic roadmap to tackle the issue.

 // JavaScript code snippet
// Data manipulation example

        var a = [];
        var c= [];


        var i;
        var ii;
var iii;
var iv;
        for (i = 0; i < data.length; i++) {

          a.push(data[i].age);

        }
          a=[...new Set(a)];
        for (ii = 0; ii < a.length; ii++) {

          c.push({'age':a[ii], 'name':[]});
        }


        for (iii = 0; iii < c.length; iii++) {
        for (iv = 0; iv < data.length; iv++) {
        if(data[iv].age == c[iii].age){c[iii].name.push(data[iv].name);}
        }
        }

        console.log(c);

On a side note, this kind of data manipulation scenario is common in everyday tasks. I've integrated functions into my JS framework to handle searching, comparing, and populating arrays based on any given value. If I find time, I'll share the source code here.

Answer №4

const info = [{
    name: 'Alice',
    age: 21
  },
  {
    name: 'Henry',
    age: 20
  },
  {
    name: 'Max',
    age: 20
  },
  {
    name: 'Jane',
    age: 21
  }
];


const ages = info.map(({
  age
}) => age);

const uniqueAges = info.filter(({
  age,
  name
}, index, arr) => {
  return !ages.includes(age, index + 1)
});

const obj = {};
const groupedNames = info.map((e) => {
  if (obj.hasOwnProperty(e.age)) {
    obj[e.age] = `${obj[e.age]},${e.name}`;
  } else {
    obj[e.age] = e.name;
  }
});
const result = uniqueAges.map((e) => {
  e.name = obj[e.age].split(',');
  return e
});
console.log(result);

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

Steps to eliminate the x icon from the text box that appears automatically in Internet Explorer

I'm currently working with a UI5 text box that includes a built-in option for clearing the text using a 'X' button. However, I've noticed that in Internet Explorer, an additional default cross mark is being added alongside the UI5 cros ...

Mastering the art of utilizing callbacks in AngularJS for consuming an API

Having trouble handling data from an API and structuring it effectively before passing it to the controller. I've created a factory that retrieves user data from the API, but the provideAllUserData function is causing issues. Below is my services.js: ...

What is the best way to invoke an API two times, passing different parameters each time, and then merge both responses into a single JSON object using a callback function?

This code snippet is currently functional, but it only retrieves the JSON response for the first set of parameters. I am looking to make multiple calls to an external API with different parameters and then combine all the responses into one concatenated J ...

What is the best way to add a URL dynamically when a click event occurs?

Here is the code where I am making an API call: export const filteredProducts = (e) => { const radio = e.target.checked; return dispatch => { dispatch({type: actionTypes.TOGGLE_LOAD}); axios.get(radio ? `/store?limit=9&skip=0&subc ...

Creating a Star Rating System Using HTML and CSS

Looking for help with implementing a Star rating Feedback on articles in Visualforce page. Came across some code that seems to fit the bill but facing issues with getting it to work when placed in a file and executed, particularly in Firefox. Any assistanc ...

Troubleshooting issues when testing Angular services using Jasmine and Chutzpah

I've been facing some challenges while attempting to test my AngularJs services with Jasmine as I encounter various errors consistently. In an effort to troubleshoot, I decided to create a simple Sum service for testing purposes but unfortunately, the ...

The error message is indicating that the function "req.assert" is not

Can you identify the issue with this code snippet (express 4.16.0, TypeError: req.assert is not a function)? userController.signupPost = function(req, res, next) { console.log(req.body); var express=require('express'); var validator = require(&a ...

Testing a service in Angular using $q is a crucial step in ensuring the functionality and

Offering a straight forward service: .factory('list', function($q, $timeout) { return { get: function() { var dfd = $q.defer(); $timeout(function () { dfd.resolve(['label1', 'la ...

Having trouble making the menu stay at the top of the page in IE7

Check out the demo here: http://jsfiddle.net/auMd5/ I'm looking to have the blue menu bar stay fixed to the top of the page as you scroll past it, and then return to its original position when scrolling back up. This functionality works in all brows ...

Use $lookup with nested subdocuments

I have four different collections that I need to connect and extract information from: "Groups", "Users", "LinkedTags", and "Photos". First, I start by retrieving all the groups from the "Groups" collection: group { id: 1, start: 10.12, linke ...

Tips on preventing right-click actions in jqGrid

While utilizing onSelectRow in a jqGrid, I have noticed that it functions properly when clicking with the left mouse button. However, when right-clicking, it still triggers the function. My aim is for the right-click to perform its usual action (such as di ...

Deleting an item in Vue.js with the removal feature

After deleting items from my list, they remain visible until I manually refresh the page. How can I fix this issue? List <tbody> <tr v-for="school in schools" v-bind:key="school.id"> <td>{{ school.id }}</td> &l ...

Retrieve the node-postgres result and store it in a separate object beyond the callback function

Currently, I am in the process of converting a data profiling script originally written in Python to JavaScript while following the Wes Bos beginner Javascript Course. This script is designed to take database connection details and a specified target tabl ...

How is it that a variable (specifically a random number) operates as a 'generator'?

Attempting to create a simple rock paper scissors game in Python TypeError: unsupported operand type(s) for +: 'generator' and 'str' An error occurred when I added a randomizer to the code: Traceback (most recent call last) <ipytho ...

How can you determine when a download using NodeJS HTTPS.get is complete?

Currently, I am facing an issue while downloading a file. My goal is to perform an action immediately after the download is complete. Specifically, I aim to import a .js file as soon as it finishes downloading. var request = https.get('https://m ...

What is preventing me from filling my array with the URL inputted by the user?

I am looking to dynamically populate an array with URLs and display them one by one as users upload files. The goal is for each user to upload a file, have it stored in the array, and then displayed on the page. Specifically, I want to generate <img/&g ...

In JavaScript, efficiently remove specific node types from a tree structure using recursion, while also maintaining and distributing qualified child nodes

Currently, I am working on a recursive function that operates on a JSON tree structure {name, type, [children]}, with the goal of removing nodes of a specific type. However, it is essential that the children of the removed node are reattached to the parent ...

Interceptors in axios do not trigger when making requests through a PHP proxy

I am currently working on a React app that will be interacting with services hosted on a remote server. During development on my local machine using the react-scripts server at localhost:3000, I disable CORS in the browser and have no issues with axios f ...

Transitioning from Three.js's CanvasRenderer to WebGLRenderer is a significant upgrade

Can a Three.js script created with CanvasRenderer be easily converted to use WebGLRenderer instead, and if yes, what is the process for doing so? ...

Separate the elements with a delimiter

I am in the process of inserting various links into a division by iterating through a group of other elements. The script appears to be as follows $('.js-section').children().each(function() { var initial = $(this).data('initial'); ...