JavaScript: transform all repetitive elements in the array

One interesting example in my code.

var array=[[1,'a'],[1,'b'],[2,'c'],[2,'b'],[2,'d'],[3,'a'],[3,'s'],[3,'w'],[3,'q'],[4,'w']]

Desired output is as below:

1   a
    b
2   c
    b
    d
3   a

This code snippet replaces duplicate numbers with an empty string.

Attempting this approach, which only compares two elements at a time.

for( var i=0; i<array.length-1; i++ ) {
        if ( array[i][0] == array[i+1][0] ) {
            array[i+1][0]='';
        }
    }   

Answer №1

In order to remove duplicate elements from an array, an external loop must be added:

   for(var x=0; x < arr.length; x++){
for( var y=0; y<arr.length; y++ ) {
        if ( arr[y][0] == arr[x][0] && y != x) {
            arr[y][0]='';
        }
    } 
}

Answer №2

The code provided below displays the data in the specified format without altering its content.

//display initial data
println( string(array[0][0]) + '  ' + array[0][1] )
var prevNumber = array[0][0]  // keep track of the previously printed data number.

for( var i=1; i<array.length-1; i++ ) {
    if ( array[i][0] == prevNumber ) {  // if the number is the same, display ' ' instead of the number.
        println( ' ' + '   ' + array[i][1] )
    } else { // when the number changes
        println( array[i][0] + '   ' + array[i][1] )
        prevNumber = array[i][0]  // update the previously printed data number.
    }
}   

Deleting a part of the data in an array is a simple task, but restoring deleted data later can be challenging or even impossible. This is the reason why the data in the array is left unmodified, and only the code for display is adjusted.

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

Navigating through an array of functions, some of which may return promises while others do not

Is there a way to efficiently iterate and execute an array of functions where some return promises, requiring the use of await, while most do not return promises, necessitating them to be set as async? for (let i = 0; i < this.steps.length; i++) { ...

Using Vue's computed property setter with an object as a prop

I have a new concept for an input component where different objects can be passed, displayed as CSV, and allow for text editing/validation with style changes based on validation results. Check out the code snippet I've been working on: <div id=&quo ...

Using PHP variables in JavaScript fetched through AJAX loading

I am currently attempting to retrieve a PHP variable from another page using AJAX in JavaScript, but it is not displaying any alerts. This is the PHP code for 'getposY': <?php include"connectdatabase.php"; $posYquery=mysql_query("Select posY ...

Typescript throws an error when attempting to return an array of strings or undefined from a function

I created a shallow differences function that compares two arrays of strings and returns either undefined (if the arrays are different lengths) or a string array containing matching characters at corresponding indexes. If the characters don't match, i ...

`Increase Your Javascript Heap Memory Allocation in Next.js`

We are facing a challenge with the development environment for our Next.js application. Issue The Javascript heap memory is consistently depleting. Here are the specific error logs: FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out ...

What is the best way to prevent a folder from being included in the next js build process while still allowing

I am faced with a challenge involving a collection of JSON files in a folder. I need to prevent this folder from being included in the build process as it would inflate the size of the build. However, I still require access to the data stored in these file ...

Choosing nested JSON elements to populate selection menus

Here is an example of JSON data format: "games": [{ "gameType": "RPG", "publishers": [{ "publisher": "Square", "titles": [{ "title": "Final Fantasy", "gameReleases": [ 2006, 2008, 2010, 2012, 2013, 2014 ] ...

Using the `map()` method in React's array

I stumbled upon an interesting example at http://codepen.io/lacker/pen/vXpAgj that closely resembles my current issue. Let's consider the following array: [ {category: 'Sporting Goods', price: '$49.99', stocked: true, name: &apo ...

Determine whether the click occurs inside or outside of a bar on a ChartJS graph

I'm currently working with a bar graph using chartJS. I'm trying to figure out how to detect where the user clicked - whether it was inside or outside of the bar region in chartJS. const waterFChart = new Chart(canvasRef.current, { plugins: [ ...

What is the best way to conceal a dynamically-loaded element on a webpage?

I wrote a script that utilizes AJAX to fetch data from a PHP file named names.php. Later in the script, I used jQuery's $(document.ready(function(){}); to attempt hiding a div when the DOM is loaded. Strangely, the $("div").hide() function isn' ...

YouTube's embedded video player is invincible and cannot be destroyed

Having trouble destroying an embedded YouTube video on the Plyr player. The player.destroy() method is being called without any errors, but it doesn't actually destroy the player. This issue is causing the previous video to load instead of a new one ...

CodeMirror version 5.62.3 is experiencing some challenges with the scrollbar functionality, editor size, and line wrapping

During my HTML/CSS/JS coding session, I encountered a challenge with CodeMirror version 5.62.3. Specifically, I was striving to make the scrollbar visible in the code editor, using C# as the language mode. However, despite setting the editor's height ...

Navigating the world of gtag and google_tag_manager: untangling

Tracking custom events in my react application using Google Analytics has been successful. Initially, I followed a helpful document recommending the use of the gtag method over the ga method for logging calls. The implementation through Google Tag Manager ...

When selecting a dropdown in Angular 5, the aria-expanded attribute remains unchanged and the 'show' class is not applied. This behavior is specific to Bootstrap dropdowns

Having an issue with the bootstrap dropdown in my Angular project. When I click on it, the dropdown-menu does not show up. The 'show' class is not being added to the dropdown and the 'aria-expanded="false"' attribute does not change to ...

Leveraging props to set the initial value of component data in Vue 3 Composition API

Currently, I am in the process of developing a search page in Vue 3 using the composition API. One of my components is responsible for displaying a snippet of data that includes specific keywords provided by the parent component. To achieve this, I need to ...

Encountering an unfamiliar property in JSX dynamic component

I am attempting to display components after dynamically determining their name, but I keep encountering this issue: Unknown property ent on the <resultComponent> tag. Please remove this property from the element. The problematic code is located w ...

Can you explain the distinction between querying a database and making a request to an endpoint?

Recently, I've been diving into learning mongoose but came across a code that left me puzzled. I'm curious as to why we include the async keyword at the beginning of the callback function when querying a database. Isn't it already asynchron ...

What is the correct way to implement the chain populate method in a Node.js application?

I am developing a blog application with node.js and react, utilizing MongoDB and Mongoose's .populate method to fetch data across collections. Currently, I have three collections: Post, User, and Category. Successfully, I managed to link the username ...

Utilizing JavaScript to dynamically resize an element within a slide as soon as the slider transitions to the following slide

RESOLVED! ISSUE FIXED! While working on my personal website using WordPress and the Smart Slider 3 plugin, I encountered a problem with the positioning and size of an element in the second slide. Despite finding a tutorial explaining how to manually trigg ...

Trigger an alert box using JavaScript after a successful submission

PHP Script Explanation The following PHP script is executed once the corresponding form has been filled out: <?php $connect = mysql_connect($h, $u, $p) or die ("Connection Failed."); mysql_select_db($db); ## Prevent SQL Inje ...