Setting values to an array based on the index of a specific name in JavaScript - a guide

How can I set values to an array if it has an index in the name field? Here is the sample data:

[
    {
        "column": "created_at[0]",
        "name": "created_at[0]",
        "type": "range",
        "value": "2022-12-26 00:00:00"
    },
    {
        "column": "created_at[1]",
        "name": "created_at[1]",
        "type": "range",
        "value": "2023-12-26 23:59:59"
    },
    {
        "column": "email",
        "name": "email",
        "type": "like",
        "value": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9dfcfcddfaf0fcf4f1b3fef2f0">[email protected]</a>"
    }
]

I need to update both the name and value of the array if the name contains an index. The expected result should look like this:

[
    {
        "column": "created_at",
        "name": "created_at",
        "type": "range",
        "value": ["2022-12-12 00:00:00", "2023-12-12 23:59:59"]
    },
    {
        "column": "email",
        "name": "email",
        "type": "like",
        "value": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7b1a1a3b1c161a121755181416">[email protected]</a>"
    }
]

I have attempted to achieve this using the following code, but it isn't working as expected:

const modifiedArray = array?.reduce(
      (accumulator, element) => ({
        ...accumulator,
        [element.name?.split("[").shift()]: element.value,
      }),
      {}
    );
    console.log(modifiedArray)

Answer №1

Here's an example showcasing the use of the Nullish coalescing assignment ??=

const grouped = array.reduce((acc, { name, value }) => {
  const baseName = name.split('[')[0];
  acc[baseName] ??= { // utilizing Nullish coalescing assignment
    column: baseName,
    name: baseName,
    type: name.includes('[') ? 'range' : 'like',
    value: []
  };
  
  if (name.includes('[')) { // it represents a range
    acc[baseName].value.push(value);
  } else {
    acc[baseName].value = value;
  }

  return acc;
}, {});

const result = Object.values(grouped);
console.log(result);
<script>
  const array = [{
      "column": "created_at[0]",
      "name": "created_at[0]",
      "type": "range",
      "value": "2022-12-26 00:00:00"
    },
    {
      "column": "created_at[1]",
      "name": "created_at[1]",
      "type": "range",
      "value": "2023-12-26 23:59:59"
    },
    {
      "column": "email",
      "name": "email",
      "type": "like",
      "value": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="42232302252f232b2e6c212d2f">[email protected]</a>"
    }
  ]; </script>

Can we make this process faster?

const grouped = array.reduce((acc, { name, value }) => {
  const splitIndex = name.indexOf('[');
  const baseName = splitIndex === -1 ? name : name.substring(0, splitIndex);
  const isRange = splitIndex !== -1;

  let entry = acc[baseName];
  if (!entry) {
    entry = acc[baseName] = {
      column: baseName,
      name: baseName,
      type: isRange ? 'range' : 'like',
      value: isRange ? [] : value
    };
  }

  if (isRange) {
    entry.value.push(value);
  }

  return acc;
}, {});

console.log(grouped)
<script>
  const array = [{
      "column": "created_at[0]",
      "name": "created_at[0]",
      "type": "range",
      "value": "2022-12-26 00:00:00"
    },
    {
      "column": "created_at[1]",
      "name": "created_at[1]",
      "type": "range",
      "value": "2023-12-26 23:59:59"
    },
    {
      "column": "email",
      "name": "email",
      "type": "like",
      "value": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="07666647606a666e6b2964686a">[email protected]</a>"
    }
  ];
</script>

Answer №2

const info = [{
    "category": "date[0]",
    "title": "date[0]",
    "format": "between",
    "info": "2022-12-26 00:00:00"
  },
  {
    "category": "date[1]",
    "title": "date[1]",
    "format": "between",
    "info": "2023-12-26 23:59:59"
  },
  {
    "category": "email",
    "title": "email",
    "format": "like",
    "info": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="60010120070d01090c4e030f0d">[email protected]</a>"
  }
];

const result = info.reduce((acc, item) => {
  const titleParts = item.title.split("[");
  const baseTitle = titleParts[0];

  if (titleParts.length > 1) {
    const index = parseInt(titleParts[1].replace("]", ""));
    if (!acc[baseTitle]) {
      acc[baseTitle] = {
        category: baseTitle,
        title: baseTitle,
        format: "range",
        info: Array(index + 1).fill(null).map(() => null)
      };
    }
    acc[baseTitle].info[index] = item.info;
  } else {
    acc[baseTitle] = { ...item
    };
  }

  return acc;
}, {});

const finalArray = Object.values(result);
console.log(finalArray);

Answer №3

const info = [
    {
        "column": "created_at[0]",
        "name": "created_at[0]",
        "type": "between",
        "value": "2022-12-26 00:00:00"
    },
    {
        "column": "created_at[1]",
        "name": "created_at[1]",
        "type": "between",
        "value": "2023-12-26 23:59:59"
    },
    {
        "column": "email",
        "name": "email",
        "type": "like",
        "value": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="086969486f65696164266b6765">[email protected]</a>"
    }
];

const output = info.reduce((result, item) => {
  const index = item.name.lastIndexOf('[');
  if (index === -1) return result.arr.push(item) && result;
  const nameVal = item.name.slice(0, index);
  let located = result.map[nameVal];
  located ? result.arr.push({column: nameVal, name: nameVal, type: 'range', value: [located.value, item.value]}) : result.map[nameVal] = item;
  return result;
}, {arr: [], map: {}}).arr;

console.log(output);

` Chrome/120
-----------------------------------------------------------------
Alexander             1.00x  |  x1000000  123  124  129  130  131
mplungjan             1.18x  |  x1000000  145  147  150  150  150
mplungjan (faster?)   1.35x  |  x1000000  166  167  175  176  186
-----------------------------------------------------------------
https://github.com/silentmantra/benchmark `
` Firefox/121
------------------------------------------------------------------
Alexander             1.00x  |  x10000000  729  753  784  799  801
mplungjan (faster?)   1.55x  |   x1000000  113  118  122  132  146
mplungjan             3.42x  |   x1000000  249  261  262  263  267
------------------------------------------------------------------
https://github.com/silentmantra/benchmark `

const info = [
    {
        "column": "created_at[0]",
        "name": "created_at[0]",
        "type": "between",
        "value": "2022-12-26 00:00:00"
    },
    {
        "column": "created_at[1]",
        "name": "created_at[1]",
        "type": "between",
        "value": "2023-12-26 23:59:59"
    },
    {
        "column": "email",
        "name": "email",
        "type": "like",
        "value": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e98888a98e84888085c78a8684">[email protected]</a>"
    }
];

// @benchmark mplungjan 

const groupedData = info.reduce((acc, { name, value }) => {
  const baseName = name.split('[')[0];
  acc[baseName] ??= {
column: baseName,
name: baseName,
type: name.includes('[') ? 'range' : 'like',
value: []
  };
  
  if (name.includes('[')) { // it's a range
acc[baseName].value.push(value);
  } else {
acc[baseName].value = value;
  }

  return acc;
}, {});

Object.values(groupedData);

// @benchmark mplungjan (faster?)

Object.values(info.reduce((acc, { name, value }) => {
  const splitIndex = name.indexOf('[');
  const baseName = splitIndex === -1 ? name : name.substring(0, splitIndex);
  const isRange = splitIndex !== -1;

  let entryInfo = acc[baseName];
  if (!entryInfo) {
entryInfo = acc[baseName] = {
  column: baseName,
  name: baseName,
  type: isRange ? 'range' : 'like',
  value: isRange ? [] : value
};
  }

  if (isRange) {
entryInfo.value.push(value);
  }

  return acc;
}, {}));

// @benchmark Alexander

info.reduce((r, item) => {
  const idx = item.name.lastIndexOf('[');
  if (idx === -1) return r.arr.push(item) && r;
  const name = item.name.slice(0, idx);
  let found = r.map[name];
  found ? r.arr.push({column: name, name, type: 'range', value: [found.value, item.value]}) : r.map[name] = item;
  return r;
}, {arr: [], map: {}}).arr;

/*@end*/eval(atob('e2xldCBlPWRvY3VtZW50LmJvZHkucXVlcnlTZWxlY3Rvcigic2NyaXB0Iik7aWYoIWUubWF0Y2hlcygiW2JlbmNobWFya10iKSl7bGV0IHQ9ZG9jdW1lbnQuY3JlYXRlRWxlbWVudCgic2NyaXB0Iik7dC5zcmM9Imh0dHBzOi8vY2RuLmpzZGVsaXZyLm5ldC9naC9zaWxlbnRtYW50cmEvYmVuY2htYXJrL2xvYWRlci5qcyIsdC5kZWZlcj0hMCxkb2N1bWVudC5oZWFkLmFwcGVuZENoaWxkKHQpfX0='));

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

The optimal and most secure location for storing and retrieving user access credentials

After receiving a list of locations accessible to the session user from the server, I am seeking the ideal location to store these roles in Angular. This will allow me to determine whether or not to display specific routes or buttons for the user. Where ...

Implementing a transition to activate upon data loading in a Vue.js component – here's how!

Currently, I am immersed in a project utilizing vue.js and vue-router. Within my Vue application, I have a section dedicated to displaying news fetched from an API that functions as a blog. To load this news data into the component, I am utilizing the rou ...

Are React component properties enclosed in curly braces?

I have a new component configured like this: type customType = differentType<uniqueType1, uniqueType2, uniqueType3>; function customComponent({q}: customType) When called, it looks like this: <customComponent {...myCustomVar} />, where myCus ...

Tips for positioning a box on top of a map in a floating manner

I am trying to figure out how to position the div with class box on top of the map in this jsbin. Can someone help me achieve this? Below is the CSS code I have for styling the box and body. body { font-family: "Helvetica Neue", Helvetica, sans-serif; ...

Tips on transferring key values when inputText changes in ReactJs using TypeScript

I have implemented a switch case for comparing object keys with strings in the following code snippet: import { TextField, Button } from "@material-ui/core"; import React, { Component, ReactNode } from "react"; import classes from "./Contact.module.scss" ...

Utilizing AngularJS to connect a dynamic result array to a table with varying layouts

I am struggling to bind a dynamic array result with a table using Angular JS in a different layout. Despite multiple attempts, I have not been successful in achieving the desired outcome. Any help or guidance would be greatly appreciated. var arr = [ ...

What steps can I take to make sure that a sub component's props are refreshed properly?

I'm encountering an issue with RTK queries in my project. I have a parent component that contains a table component. When a refresh event occurs, such as deleting data, the parent component receives updated data and passes it down to the child compone ...

Choosing to maintain an open server connection instead of regularly requesting updates

Currently, I am in the process of developing an innovative online presentation tool. Let's dive into a hypothetical situation: Imagine one person is presenting while another connects to view this presentation. >> How can we ensure that the vie ...

Issues with the audio on ExpressJS video streaming can be quite vexing

After multiple attempts to run an ExpressJS web server that serves videos from my filesystem, I've encountered a frustrating issue. Whenever a video is played, there are constant popping sounds and eventually the audio cuts out completely after 3-10 m ...

Retrieving Information with the Fetch API in Node.js and Storing it in a MongoDB Database

I'm a newcomer to mongooseDB and am currently experimenting with inserting data from an API into the database. It successfully creates the Collection, but unfortunately it is not generating the documents. Any suggestions on what I might be doing incor ...

Tips for aligning a dropdown button with the other elements in your navbar

I followed the code outline from a tutorial on We3schools, but I'm having an issue with the button not aligning correctly with the navbar. https://i.sstatic.net/fSRIT.png I attempted to adjust the code for proper alignment before publishing, but was ...

Is there a glitch preventing the connection between HTML and CSS in Notepad++ even though the link is correct?

I have encountered a puzzling situation that has left me scratching my head in confusion. Despite being a rookie, I've had experience with linking CSS files before and can't understand why it's not working this time around. This issue is per ...

String variable representing the name of a React element

As I was reviewing the source code of a React UI library, I stumbled upon an interesting code pattern that I will simplify here: function Test() { let Button = "button"; // ... return <Button>Click me</Button>; } I'm curious about ...

Create a single line of content for a carousel display

Seeking a solution where I can have a container that slides sideways without stacking in rows, I have exhaustively searched for answers using different keywords like single row, inline, flexbox, and grid but to no avail. Any assistance will be highly appre ...

Using PHP to validate a read-only textbox

I am trying to implement validation on a Datepicker that is set to readonly, but I am facing issues with my current code. Can someone please assist me? Below is the JavaScript code used for error trapping: <script type="text/javascript"> $(func ...

The specified property 'length' is not found on type OkPacket within the mysql2 module

In my code example below, I am simply showcasing a specific scenario: this.getCode = (code: string): Promise<codeObject | false> => { return new Promise((resolve, reject) => { pool.query('SELECT * FROM ?? WHERE code = ...

Sending a JavaScript object as a prop in a React component

Currently, I am enrolled in a React course that requires us to pass a single JavaScript object as props to a React application. Here's the code snippet I have been working on: import React from 'react'; import ReactDOM from 'react-dom& ...

Create an interface object in TypeScript with no initial properties

I'm currently developing an app with angular 5 (TS) and I've encountered a problem while trying to initialize an empty object of my interface. The solution that I found and attempted is as follows: article: Article = {} as Article; However, ...

The useEffect hook is not successfully fetching data from the local db.json file

I'm attempting to emulate a Plant API by utilizing a db.json file (with relative path: src\plant-api\db.json), and passing it from the parent component (ItemList) to its child (Item) but I am facing an issue where no data is being displayed ...

"Utilizing OpenLayers to display markers coupled with interactive pop

I am struggling to implement a map with markers on my website. I want users to be able to click on these markers and view additional information, similar to how it works in Google Earth. Although I have the map and markers set up, I am having trouble getti ...