0

I am trying to display the contents of an array in a more readable way, this is the array:

["malevolent", "pariah", "judicious", "pariah", "judicious"]

I'm simply adding that array to an HTML element to display it, but I want to display it like this:

malevolent, pariah x 2, judicious x2

How would I do this?

Matthew Starkey
  • 677
  • 2
  • 8
  • 16

4 Answers4

1

You can try the following:

var myArray = ["malevolent", "pariah", "judicious", "pariah", "judicious"];
var resultArray = [];
var countArray = [];

for(index in myArray) {
    var element = myArray[index];
    var isInArray = resultArray.indexOf(element);
    if(isInArray !== -1) {
        var tmpCnt = countArray[isInArray];
        tmpCnt++;
        countArray[isInArray] = tmpCnt;
    } else {
        resultArray.push(element);
        countArray.push(1);
    }
}
console.log(resultArray);
console.log(countArray);
Dharmang
  • 3,018
  • 35
  • 38
  • 1
    Why should the OP try this? Please **explain** your solution, don't just post code. What does it do, how does it work? – Felix Kling Jan 25 '14 at 06:05
  • @FelixKling, loop through every element in the source array, check if the element existing in destination array. if the element does not exist in the destination array, add to the same and 1 to the count array. and if the element exists just updated the count array to +1, is it clear? – Dharmang Jan 25 '14 at 06:06
1

It's quite simple actually:

var myArray = new Array("a", "b", "c", "b", "a");
var newObject = {};
// Iterate over the array
for(var i = 0; i < myArray.length; i++){
    // If the new object already contains the key (e.g. a, b, or c), increment value by one
    if(myArray[i] in newObject){
        newObject[myArray[i]]++;   
    } else {
        // Otherwise add a key (e.g. a, b, or c) to the object and assign 1 to it (first occurence)
        newObject[myArray[i]] = 1;   
    }
}
// Write the resulting object to console
window.console && console.log(newObject);

newObject contains a list of keys (a,b,c) and values (number of occurrences of each key). You can than use that data to output it in any format you like, but that's left up to you as an excercise.

Jay
  • 2,141
  • 6
  • 26
  • 37
  • @jenson-button-event I was asked to explain that code and I did so, because that was a fair request. Anyone who has more than 3 days of experience in JS (including Felix Kling) doesn't need any explanation to understand this code since it is perfectly clear and concise. And now stop trolling please. – Jay Jan 25 '14 at 06:19
  • Oh, funny, I thought you mentioned me because I saw this comment in in my inbox (because I'm the only one who commented). FWIW, I just upvoted your answer before you commented ;) Out of all the ones given here, yours provides a good explanation. – Felix Kling Jan 25 '14 at 06:28
  • Thanks Felix, I mentioned you (unintentionally) when I responded to jenson button who tried to troll this q/a. :-) – Jay Jan 25 '14 at 06:34
0

Felix Kling provided a Link to an answer on how to count your elements. I just shamelessly use the reduce method described there and then just iterate over the object to build a string.

var a = ["malevolent", "pariah", "judicious", "pariah", "judicious"].reduce(function (acc, curr) {
    if (typeof acc[curr] == 'undefined') {
        acc[curr] = 1;
    } else {
        acc[curr] += 1;
    }

    return acc;
}, {});

var out = "";

for (var k in a) {
    out += k + " x " + a[k] + "; ";
}

console.log(out);
Grmpfhmbl
  • 1,119
  • 12
  • 24
-1

try this

      var arr = new Array("malevolent", "pariah", "judicious", "pariah", "judicious");

    var new_arr1 = new Array(); // for containing distinct values like pariah
    var new_arr2 = new Array(); // for containing distinct values count like 2 for pariah

   // both will be on same index in new_arr1 and new_arr2

    for(var i=0; i<arr.length; i++)
    {
          // fetch every value of arr

        var indx = $.inArray(arr[i], new_arr1); // check value is exists in new_arr1 and get index

        if(indx > -1) // values exists in new_arr1
        {
             var v = new_arr2[indx]+1; // increment the previous count +1
             new_arr2[indx] = v; // update it on the index of new_arr2
        }
        else         
        {
           // if value not in new_arr1 means the value comes first time
            var l = new_arr1.length;
            new_arr1[l] = arr[i]; // insert value in new_arr1
            new_arr2[l] =  1;         // initate count 1 for the same index of new value in new_arr2 
        }
    }


// now new_arr1 will contains the distinct values
// and new_arr2 contains the count for distinct values 
// eg new_arr1[0] = 'malevolent';
//    new_arr2[0] = 1;

//    new_arr1[1] = 'pariah';
//    new_arr2[1] = 2;


//  now you can fetch distinct values and their count like given below
    for(var i=0; i<new_arr1.length; i++)
    {
       var str = new_arr1[i]+" X "+new_arr2[i];
       alert(str);
    }

See FIDDLE

Satish Sharma
  • 9,547
  • 6
  • 29
  • 51