Minimize a collection of JavaScript objects

I am working with an Array of objects where I need to return the collection as an Object, with the key names being the indexes of their length. Additionally, I have to filter this object based on its values.

Check out my code snippet below:

const data = [
  { index: 1, value: "111" },
  { index: 2, value: "121" },
  { index: 3, value: "111" },
  { index: 5, value: "111" },
  { index: 6, value: "121" },
  { index: 7, value: "121" },
];

const getGroupBy = (data) => {
  return data.reduce((acc, curr, currIndex, arr) => {
    const val = curr.value;
    const idx = curr.index;
    const fValues = arr.filter((el) => el.value === val).map(el => el.index);
    if (acc.hasOwnProperty(currIndex)) {
      acc[currIndex] = arr.filter((el) => el.value === val);
    } else {
      Object.assign(acc, { [0]: [idx] });
    }
    return acc;
  }, {});
};

console.log(getGroupBy(data));

The expected output from my code is :

{
    0: [1,3,5],
    1: [2,6,7]
}

Answer №1

Do you think it would be more practical to key the arrays by their values instead of 0 and 1?

Here's a way to condense the code and either use 0/1 keys or keys based on the value:

const data = [
  { index: 1, value: "111" },
  { index: 2, value: "121" },
  { index: 3, value: "111" },
  { index: 5, value: "111" },
  { index: 6, value: "121" },
  { index: 7, value: "121" },
];

const indices = data.reduce((acc,{index,value}) => {
  (acc[value] ??= []).push(index);
  return acc;
},{})
console.log({...Object.values(indices)})
// or 
console.log(indices);

A different approach is suggested here

const data = [
  { index: 1, value: "111" },
  { index: 2, value: "121" },
  { index: 3, value: "111" },
  { index: 5, value: "111" },
  { index: 6, value: "121" },
  { index: 7, value: "121" },
];

const indices = data
  .reduce((acc,{index,value},i, arr) => {
    (acc[value] ??= []).push(index);
    return i < arr.length ? acc : {...Object.values(acc) }; // return the desired format at the end
  },{});

console.log(indices);

Answer №2

One approach could be to group and store the values in an object.

const
    data = [{ index: 1, value: "111" }, { index: 2, value: "121" }, { index: 3, value: "111" }, { index: 5, value: "111" }, { index: 6, value: "121" }, { index: 7, value: "121" }],
    result = Object.assign(
        {},
        Object.values(data.reduce((r, { index, value }) => ((r[value] ??= []).push(index), r), {}))
    );

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №3

It is crucial to follow these steps for cleaner code:

  1. {index: [value]}
  2. {0: value}

This approach will greatly enhance the readability of your code.

  const data = [
    { index: 1, value: '111' },
    { index: 2, value: '121' },
    { index: 3, value: '111' },
    { index: 5, value: '111' },
    { index: 6, value: '121' },
    { index: 7, value: '121' },
  ];

  const getGroupBy = (data) => {
    return data.reduce((acc, curr) => {
      if (acc[curr.value]) acc[curr.value].push(curr.index);
      else acc[curr.value] = [curr.index];
      return acc;
    }, {});
  };
  console.log(getGroupBy(data));
  console.log({ ...Object.values(getGroupBy(data)) });

Answer №4

In my recent code snippet, I made use of the reduce function to manipulate data, with a slight alteration on the final iteration to achieve the desired result.

Utilizing this approach is quite handy in various scenarios where the end goal may only be reached during the last item iteration, signifying completion of processing all elements.

const data = [
  { index: 1, value: "111" },
  { index: 2, value: "121" },
  { index: 3, value: "111" },
  { index: 5, value: "111" },
  { index: 6, value: "121" },
  { index: 7, value: "121" },
];

const getGroupBy = (data) => {
  return data.reduce((acc, curr, index) => {
    const val = curr.value;
    const idx = curr.index;
    var key  = val;
     
    if (!acc[key]) {
      acc[key] = [];
    }
    acc[key].push(idx);

     if (index == data.length-1) {
      return Object.values(acc).reduce((a,c, i)=> { a[i]=c; return a;}, {});
    }
    return acc;
  }, {});
};


console.log(getGroupBy(data))

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

Using a JSON file as a variable in JavaScript

Hello there everyone! I am looking to create a multilingual landing page. The idea is to have a language selection dropdown, and when a language is chosen, JavaScript will replace the text with the corresponding translation from a JSON file. However, I a ...

Exploring the implementation of the meta robots tag within Joomla 2.5's global settings

Encountering a peculiar issue with Joomla 2.5 and the Meta robots tag. Joomla seems to have a flaw where regardless of the URL, as long as there is a valid article id, it will generate a page. For instance: The id '61' is valid but leads to a ...

Issue experienced with Vue2 where utilizing a computed property to filter a nested v-for structure

I have a unique HTML challenge that requires me to iterate through an unconventional data setup. The information is retrieved in two separate parts from Firebase: one for categories and another for businesses. The structure of the data is as follows: Busi ...

How to align two <select> elements side by side using Bootstrap

The issue I am encountering is that these two select elements within the same control-group are being displayed vertically when I want them to be displayed horizontally. I attempted using inline-block in CSS, but there are other <div> elements with ...

Creating a task management application using AXIOS and VUE for easy data manipulation

I am currently working on a small app to enhance my skills in VUE and Axios. However, I am facing a roadblock when it comes to the update functionality. I am struggling to pass the ID to the form for updating and despite watching numerous tutorial videos ...

Extracting information from ul li div elements and saving it in JSON format

I have been pondering this issue for the past few hours and haven't been able to find a solution. Essentially, I have a list structured like this <ul class="list"> <li class="user"> <div class="name">Name</div> ...

Utilizing Ajax for Dynamically Filling a Dropdown Menu

My journey into the world of Ajax has led me to a state of confusion and frustration. The task at hand is to populate the first box with customer data from the database, then use the customerID to retrieve all vehicleID's using the select.php script. ...

retrieve data from jsp page using ajax request

I've coded this JSP snippet Map<String, Long> map = new HashMap<String, Long>(); map.put("A", 10L); map.put("B", 20L); map.put("C", 30L); JSONObject json = new JSONObject(); json.accumulate ...

Tips for adding an asterisk to the label of a Material-UI switch component

I am trying to include an asterisk symbol in the label by passing a required prop with a property, but it doesn't seem to be functioning correctly. <FormControlLabel control={ <Switch onChange={event => ...

What does getsession.insert in the Ace Editor return?

Seeking clarification on the return values of the addMarker and insert functions in ace editor's edit session. The official documentation lacks detail, leaving me uncertain. Refer to the edit session API for more information. I've encountered i ...

Set the background-color of each <td> element to be equal to a value in the array, with each group of three elements having the same

I am trying to color every <td> element in a row of three columns with the same color using the following code: for (var i = 0; itr < $("td").length; i++) { $("td").eq(i).css("background-color", Colors[i]); } However, this code colors each i ...

The browser automatically adds a backslash escape character to a JavaScript object

When attempting to send an MQTT message to a topic from my angular app, the message needs to be in a specific syntax: { "Message": "hello" //the space after : is mandatory } However, upon sending the message in the correct format, the browser aut ...

Failed to cast value "undefined" to ObjectId in the "_id" path for the model "User"

I've been encountering an issue that I can't seem to resolve despite searching on Stack and Google. My ProfileScreen.js is meant to display a user's profile, but when attempting to view the profile, I receive this error: "Cast to ObjectId fa ...

Transmit updated value to masterpage upon selection alteration

In my current project using ASP.NET, I have a MasterPage that includes a navigation bar with different options. One of the options leads to another page where the company now requires me to pass a parameter through the link. After some research, I managed ...

What is the best method for selecting only files (excluding folders) in Gulp?

I have a gulpfile where I am injecting files into an appcache manifest in this manner: var cachedFiles = gulp.src('**', {read: false, cwd: 'build'}); gulp.src('src/*.appcache', {base: 'src'}) .pipe($.inject(cachedF ...

Is there a way to segment a string into words using a dictionary and finding the longest match in JS/Jquery?

Imagine you have a string like this: var str = "thisisinsane"; and a list of words from a dictionary such as: var dic = [ "insane", "i", "is", "sin", "in", "this", "totally" ]; How can we separate the words in str? In this specific case, there a ...

Utilizing PHP to dynamically generate href links based on radio button selection in real-time interaction with JavaScript

Currently, I am utilizing the MVC framework within Codeigniter and I have a view that contains a link. It's important to mention that the href value is generated by calling a PHP function which takes 'auth/mylogin' as a parameter: <a hre ...

Implementing a Popover Notification When Clicked

I'm a beginner at this. I came across an example of a popover message box in the link provided below. I attempted to implement it, but for some reason, it's not working. Could I be overlooking something? Alternatively, is there a simpler way to ...

Show categories that consist solely of images

I created a photo gallery with different categories. My goal is to only show the categories that have photos in them. Within my three categories - "new", "old", and "try" - only new and old actually contain images. The issue I'm facing is that all t ...

Using ReactJS to Deconstruct Data within Class Components

I have a file named Context.js with the following content: const AppContext = createContext({ // ... color palette scheme color1: '#ADBDDB', color2: '#7F8EB2', color3: '#546287', color4 ...