Consolidate duplicate list entries and adjust the CSS as needed

Imagine I have an array like this:

myarray = ["apple", "apple", "apple", "potato", "apple"];

myarray = ["apple", "apple", "apple", "potato", "apple"];
           
             function listCreate(data) {
  var output = '<ul>';
  $.each(data, function(key, val) {

  output += '<li">';
  output += '<h4 >' + val + '</h4>';
  output += '</li>';
  
  });
  output += '</ul>';
  $('#mylist').html(output);
}
listCreate(myarray);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mylist">
    </div>

I generate a list using jQuery

And I need to merge n repeating values and change the li height to n*50px

Example

myarray = ["apple", "apple", "apple", "potato", "apple"];
<ul>

<li style="background:#A6445E; height:150px;">apple</li>
<li style="background:#FFD433; height:50px;">potato</li>
<li style="background:#A6445E; height:50px;">apple</li>

</ul>

Example

myarray =["potato", "volvo", "volvo", "potato", "apple"];

<ul>

    <li style="background:#A7777E; height:50px;">potato</li>
    <li style="background:#FFD433; height:100px;">volvo</li>
    <li style="background:#A4565E; height:50px;">potato</li>
    <li style="background:#A2125E; height:50px;">apple</li>

</ul>

Answer №1

To eliminate consecutive duplicates in an array, simply create a new array using the original one, but skipping duplicates that appear one after the other:

myarray = ["apple", "apple", "apple", "potato", "apple", "apple"];

var temp = myarray[0];
var fixedMyArray = [temp]; 
var myArrayCounter = [];
var counter = 1;
for (var i = 1; i < myarray.length; i++) {
    if (temp != myarray[i]) {
        temp = myarray[i];
        fixedMyArray.push(temp);
        myArrayCounter.push(counter);
        counter = 1;
    }
    else
    {
        counter++;
    }
}
myArrayCounter.push(counter);

function createList(data,dataCounter) {
    var output = '<ul>';
    var temp = 50;
    for(var i = 0; i < data.length; i++)
    {

        output += '<li style="background:#A7777E; height:' + temp*dataCounter[i] + 'px;">';
        output += '<h4 >' + data[i] + '</h4>';
        output += '</li>';

    }
    output += '</ul>';
    $('#mylist').html(output);



}
createList(fixedMyArray,myArrayCounter);

Then use fixedMyArray and myArrayCounter in place of myarray inside your function.

createList(fixedMyArray,myArrayCounter);

Check out the JSFiddle demo here: http://jsfiddle.net/jpdjbcjt/1/

Answer №2

If you need to implement a counter to determine the correct class rather than the correct style, there is a solution using jQuery.
Here is the code snippet for HTML:

<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.9.1.min.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
  <div id="mylist"></div>
</body>
</html>

This is the CSS code:

.small {
  background:#FFD433;
  height:50px;
}
.large {
  background:#A6445E;
  height:150px;
}

And here is the Javascript code:

var myarray = ["apple", "apple", "apple", "potato", "apple"], 
  listCreate = function  (data) {
  var output = $('<ul>'),
    listItem = $('<li>'),
    i,
    length = myarray.length - 1,
    counter = [];
  for(i = 0; i <= length; i += 1) {
    counter[data[i]] = counter[data[i]] + 1 | 1; 
    listItem
    .clone()
    .text(data[i])
    .addClass((counter[data[i]] === 1)? 'large': 'small')
    .appendTo(output);
  }
  $('#mylist').append(output);
};
listCreate(myarray);

For more details, you can visit jsbin.com:
http://jsbin.com/covakuseru/1/edit?html,css,js,output

Answer №3

Give this a shot:

Fiddle Link

The custom function function generate(array, colors) requires two parameters: array (

["potato", "potato", "volvo", "volvo", "potato", "apple", "apple", "banana"]
) and colors (
["#A7777E", "#FFD433", "#A4565E", "#A2125E", "#FFD433"]
), both should be arrays.

HTML:

<div id="myList"></div>

JavaScript:

function generate(array, colors) {
    var newArray = [];
    var counts = {};
    var c = 0;
    var unique = '1';
    for (i = 0; i < array.length; i++) {
        if (array[i + 1] != array[i] || i == (array.length - 1)) {
            newArray.push(array[i]);
            if (array[i] != array[i - 1]) {
                counts[unique] = 1;
            }
            unique++;
        } else {
            c = c === 0 ? 1 : c;
            counts[unique] = ++c;
            c--;
        }
    }
    $('#myList').append('<ul></ul>');
    for (i = 0; i < newArray.length; i++) {
        $('ul').append('<li class="' + i + '">' + newArray[i] + '</li>');
        $('.' + i).css({'height': 50 * counts[i + 1] + 'px', 'background-color': colors[i]});
    }
}

generate(["potato", "potato", "volvo", "volvo", "potato", "apple", "apple", "banana"], ["#A7777E", "#FFD433", "#A4565E", "#A2125E", "#FFD433"]);

function generate(array, colors) {
    var newArray = [];
    var counts = {};
    var c = 0;
    var unique = '1';
    for (i = 0; i < array.length; i++) {
        if (array[i + 1] != array[i] || i == (array.length - 1)) {
            newArray.push(array[i]);
            if (array[i] != array[i - 1]) {
                counts[unique] = 1;
            }
            unique++;
        } else {
            c = c === 0 ? 1 : c;
            counts[unique] = ++c;
            c--;
        }
    }
    console.log(counts);
    console.log(newArray);
    $('#myList').append('<ul></ul>');
    for (i = 0; i < newArray.length; i++) {
        
        $('ul').append('<li class="' + i + '">' + newArray[i] + '</li>');
        $('.' + i).css({'height': 50 * counts[i + 1] + 'px', 'background-color': colors[i]});
    }
}

generate(["potato", "potato", "volvo", "volvo", "potato", "apple", "apple", "banana"], ["#A7777E", "#FFD433", "#A4565E", "#A2125E", "#FFD433"]);

generate(["potato", "volvo", "volvo", "potato", "apple"], ["#A7777E", "#FFD433", "#A4565E", "#A2125E"]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="myList"></div>

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

What is the functionality of Mongoose for handling multiple updates?

Array; arr=[ { id: [ '5e6e9b0668fcbc7bce2097ac', '5e6e9b0e68fcbc7bce2097af' ], color: [ 'a', 'b' ] } ] Models; const varyant = Models.varyant function; Promise.all( arr.map((item)=>{ return var ...

Utilize Javascript to trigger AJAX refreshes only when necessary

I have developed a web application that displays data fetched from an AJAX request to a PHP script on the same server. This particular application involves playing music from Spotify, and in order to ensure the displayed information is always up-to-date ...

Displaying Multiple HighCharts on a single AngularJS page

As a beginner with HighCharts, I am working on adding two Highcharts to the same page that will access the same data source but display different pieces of data for each graph. For example, the categories will remain constant while the series[] will vary. ...

set ajax url dynamically according to the selected option value

My form features a select box with three distinct choices <select id="tool" name="tool"> <option value="option1">Option1</option> <option value="option2">Option2</option> <option value="option3">Option3</ ...

Creating a webpage with a layout that features three full-length columns using

body { background-color: blueviolet; } .leftcolumn { width: 30%; height: 100%; float: left; background-color: brown; } .middlecolumn { float: left; background-color: yellowgreen; width: 60%; height: 100%; } <body> <div class= ...

What is the proper method for passing arguments to a function?

I'm facing an issue with a function in nodejs that uses res.execSync with multiple parameters. More information can be found here: https://github.com/xdenser/node-firebird-libfbclient The function format is as follows: function execSync(param1, ...

Error retrieving data from the ngresource properties resource

In the code snippet below, I have a simple factory that requests a json object containing location information. The requests are successful and the data is present in the object. However, there seems to be a scope problem as I am unable to access the prope ...

Learn how to incorporate a click event with the <nuxt-img> component in Vue

I am encountering an issue in my vue-app where I need to make a <nuxt-img /> clickable. I attempted to achieve this by using the following code: <nuxt-img :src="image.src" @click="isClickable ? doSomeStuff : null" /> Howeve ...

unable to retrieve the value of the table row with a particular class designation

I'm currently working with a table code and I need to retrieve the value of the table row with the class "highlight". However, when trying to do so with the code below, I'm getting a null result. Can someone please assist me? Table name: itemtab ...

Utilize Angular to simultaneously filter search results by URL and make selections in a dropdown menu

As a newcomer to the Angular JS framework, I have successfully created a client-company table where clients can be filtered by company name using a drop-down menu. However, I am now looking to implement a filtering mechanism based on the URL structure su ...

Button Fails to Respond on Second Click

I have a button that triggers a JavaScript function. This function, in turn, initiates two sequential AJAX calls. Upon completion of the first call, it performs some additional tasks before proceeding to the second AJAX call. The button functions correctl ...

Acquiring a property from an object that is specified within a function

I have created an object with properties inside a function: function createObject() { const obj = { property1: value, property2: value } } How can I access this object from outside the function? Would redefining it like ...

Unable to get spacing correct on loading page

My attempt at creating a loading page using CSS and HTML has hit a roadblock. I'm trying to show a loading bar that ranges from 0% to 100%. Despite my use of justify-content: space-between, I can't seem to get it right. I've searched through ...

Substituting ng-init with scope variables results in failure

Why is nothing rendering when I try to use scope instead of ng-init in my AngularJS code below? <!doctype html> <html ng-app="myApp" ng-controller="myCtrl"> <head> <title>Bookshop - Your Online Bookshop</title&g ...

Is there a way to send all the results of a Flask database query to a template in a way that jQuery can also access

I am currently exploring how to retrieve all data passed to a template from a jQuery function by accessing Flask's DB query. I have a database table with customer names and phone numbers, which I pass to the template using Flask's view method "db ...

What could be the reason for Google Maps producing a static map instead of a dynamic one?

Here is a snippet of code that showcases Google Map integration: <div class="col span_1_of_3 gMapHolder"> </div> Utilizing JQuery: $(document).ready(function () { alert($(".mapUse").text()); var k = $(".mapUse").text(); var embed ...

css subcategories - divs failing to meet css criteria

I am encountering an issue where my subclass is not working on DIV elements. While the CSS rules are able to match inline tags like span and a, they do not seem to work with div. Please refer to the example provided below: <style> .row { disp ...

Finding the data type based on the button clicked with javascript: A beginner's guide

I am trying to work with a PHP function that generates dynamically created divisions. Each of these divisions contains a different data type and a button. How can I extract the data type of a division when the user clicks on the submit button using JavaScr ...

javascript image alert

I want to upgrade a basic javascript alert to make it look more visually appealing. Currently, the alert is generated using if(isset($_GET['return'])) { // get a random item $sql = "SELECT * FROM pp_undergroundItems AS u LEFT JO ...

The initial execution of the getDocs function may encounter some difficulties

Whenever a user connects from localhost:3000/ (which automatically redirects to /profile), I try to fetch all documents from Firebase. However, it does not work on the first attempt. Strangely, upon refreshing the page, it successfully retrieves the docume ...