Finding and merging duplicate values within a Javascript array

I am working with a dynamically generated array that looks like this:

var myArray = ("0% { left:74px; top:202px; }"   , "44% { left:427px; top:122px; }", "0% { font-size:11px; }", "55% { font-size:49px; }" );

Within the array, there are 2 entries that have the same starting value of 0%. I'm trying to figure out how to identify and combine these duplicate entries. Here's an example of what I would like to achieve:

from:
0% { left:74px; top:202px; },
0% { font-size:11px; },

to
0% { left:74px; top:202px; font-size:11px;},

Any suggestions on how to accomplish this would be greatly appreciated.

Note: I have also made sure to edit the code to ensure it is a valid array.

Answer №1

This snippet showcases an array literal consisting of just a single member. It's crucial to properly close the strings between the commas in order to clearly separate each member within the array. One approach would be to convert each member into an object literal and leverage JSON methods to seamlessly switch between string representation and object structure. By transforming them into objects, you can easily apply mixin techniques to combine similar members for enhanced functionality.

Answer №2

So, if I understand correctly, you're displaying the contents of your array and this is the result you're seeing, correct?

If that's the case...

for(let i = 0; i < myArray.length; i++){
  for(let j = i + 1; j < myArray.length; j++){
      if(i == j) continue;
      if(myArray[i].substring(0,3) == myArray[j].substring(0,3)){//found a match for the first 3 characters
         myArray[i] = myArray[i].substring(0,3) + myArray[j].replace(/\{(.*?)\}/,"$1 ;") + myArray[i].substring(4);

        myArray.splice(j--, 1);//remove the duplicate and decrement the counter to avoid skipping an element now that the array size has changed

      }
  }
}

I haven't tested this code, but it should be similar to what you need :)

Oh, you made some edits. What you have now doesn't look like an array at all...but you're getting warmer.

I believe "array" might be a reserved keyword...

var myArray = ("0% { left:74px; top:202px; }", "44% { left:427px; top:122px; }", "etc...", "etc...");

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

How to include a file within another file in Node.js

When including one JavaScript file into another, I typically use the following syntax: var userControllerObj = require("../controller/userController"), userController = new userControllerObj.UserGatewayController(); I'm curious if I can u ...

How to retrieve a specific property from a nested array within a multidimensional array in PHP

I am currently iterating over one array with the following structure: array:8132 [ 0 => {#551 "address_id": "94e224af-135f-af31-3619-535acfae9930" "fiber_phase": "101" "parsed_hash": "1bc7fb114ee10d7cb9cea10693d238b5" "min_number": 400 "max ...

"Hiding elements with display: none still occupies space on the

For some reason, my Pagination nav is set to display:none but causing an empty space where it shouldn't be. Even after trying overflow:hidden, visibility:none, height:0, the issue persists. I suspect it might have something to do with relative and ab ...

Locate and dismiss a toast message (Toastr)

I have a webpage where I can add multiple popup notifications called toasts dynamically using the toastr plugin found at https://github.com/CodeSeven/toastr. Each toast has an Ok link that, when clicked, should only close that specific toast and not all v ...

Synchronization-free API and callback functions

I am in need of utilizing an asynchronous service. My current approach involves sending data to this service using PHP and CURL, as well as receiving data from a URL provided by the service. How can I effectively respond or wait for feedback from this serv ...

Leverage the power of integrating Power BI with Javascript to easily retrieve an

I have embarked on a mission to integrate PowerBI into my web application. Below is the code snippet that I have implemented: window.config = { instance: 'https://login.microsoftonline.com/', tenant: 'common', //COMMON OR YOU ...

Is there a way to reposition a popup window to the center of the page after launching it?

popup = window.open(thelink,'Facebook Share','resizable=1,status=0,location=0, width=500,height=300'); My goal is to perfectly center this popup window both vertically and horizontally. ...

Unable to send image file and string via XHR is causing issues

This task may seem straightforward, but I've been struggling with it for hours. My goal is to upload an image file along with stringified coordinates to crop the image on the server-side. Below is my client-side code: var formdata = new FormD ...

ReactJS: An error occurred - TypeError: this.state.items.map is not a function

As a beginner in ReactJS, I am working on my first project which is a To-Do List with drag and drop feature, add, delete, and edit functionalities. I encountered an error while trying to map an array upon submitting a text to add an item to the items array ...

Tips for evaluating an array of objects in JavaScript

Welcome to the world of coding! Here's a scenario with an array: [ { "question1": "Apple", "question2": 5, "question3": "Item 1" }, { "question1": ...

When making a Post Request, the Req.body is found to be empty

Here is the code snippet from various files: In App.js file: app.use(express.json({limit:"30mb",extended:true})); app.use(express.urlencoded({extended:true})); In route.js file: router.route("/register").post(registerUser) Importin ...

Challenge with delayed function execution in AngularJS

In my Angular application, I am encountering a problem in the following scenario. There are three crucial files: MainCtrl.js Upon loading the application, the init() function in MainCtrl.js is triggered, which then calls the flowService as shown below: ...

Issue: Exceeding rendering limit. React has a restriction on the number of renders to avoid endless loops

I'm in the process of creating a basic to do list using React, and I've encountered an issue with the handleSubmit() function that I can't seem to resolve. import React, { useState } from "react"; function TaskList() { const [ta ...

How to correctly serialize nested maps in JQuery ajax data for sending?

var locationData = { "location" : { "name" : $("#user_loc_name").val(), "street_address" : $("#user_loc_street_address").val(), "city" : $("#user_loc_city").val(), "province" : ...

What is the best way to modify Mega Menus using JavaScript?

I am currently managing a website that features "mega menu" style menus. These menus consist of nested <UL> elements and contain approximately 150 to 200 entries, resulting in a heavy load on the page and posing challenges for screen readers. To add ...

The project is not being recognized by 'webpack' when running within it

Every time I attempt to execute 'webpack' in my project, the command line shows me this error message: 'webpack' is not recognized as an internal or external command, operable program or batch file. I have installed webpack using th ...

`Exit function in Vue.js: A step-by-step guide`

Here is a code snippet in vue.js which includes an async function: async up(id, point){ this.change = true const pId = id + '-' + firebase.auth().currentUser.uid db.collection('answer').d ...

Is there a way to obtain asynchronous stack traces using Node.js and TypeScript?

When working with TypeScript, I encountered an issue with stack traces. It seems that only the bottommost function name is displayed. My setup includes Node.js v12.4.0 on Windows 10 (1803). Below is the code snippet: async function thrower() { throw new ...

Can you explain the distinctions among <Div>, <StyledDiv>, and <Box sx={...}> within the MUI framework?

When exploring the MUI documentation, I came across a table of benchmark cases that can be found here. However, the differences between the various cases are not clear to me. Can someone please explain these variances with real examples for the following: ...

Exploring the concept of unprojection in three.js

Check out this jsfiddle example of what I am trying to achieve - seeing a 3D object drawn exactly behind the cursor as it moves across the screen. http://jsfiddle.net/ksRyQ/3551/ unp = p.unprojectVector(new THREE.Vector3( mx - (window.innerWidth/2), (wi ...