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?

2
  • it means pariah is two times in array Commented Jan 25, 2014 at 5:54
  • Just count the elements in the array: stackoverflow.com/q/5667888/218196. I assume you know how to do string concatenation and change the content of an HTML element. Commented Jan 25, 2014 at 5:56

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

@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.
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.
Thanks Felix, I mentioned you (unintentionally) when I responded to jenson button who tried to troll this q/a. :-)
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);

2 Comments

Why should the OP try this? Please explain your solution, don't just post code. What does it do, how does it work?
@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?
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);

Comments

-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

5 Comments

Why should the OP try this? Please explain your solution, don't just post code. What does it do, how does it work?
i am updating the answer
@FelixKling see my updated answer and the fiddle now. you will find how this code works.
But you still haven't explained what your code does. How should the OP learn from that?
@FelixKling bro now the answer is explained. and i thing you will also understand the code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.