please tell me any good algorithm/code to get list of unique values from array and count of its occurrence in array. (i am using javascript).
For a method that will strip the duplicates from an array and returns a new array with the unique values, you may want to check the following Array.unique implementation. With an O(n2) complexity, it is certainly not the quickest algorithm, but will do the job for small unsorted arrays.
It is licensed under GPLv3, so I should be allowed to paste the implementation here:
// **************************************************************************
// Copyright 2007 - 2009 Tavs Dokkedahl
// Contact: http://www.jslab.dk/contact.php
//
// This file is part of the JSLab Standard Library (JSL) Program.
//
// JSL is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3 of the License, or
// any later version.
//
// JSL is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see .
// ***************************************************************************
Array.prototype.unique =
function() {
var a = [];
var l = this.length;
for(var i=0; i
You would be able to use it as follows:
var myArray = new Array("b", "c", "b", "a", "b", "g", "a", "b");
myArray.unique(); // returns: ["c", "g", "a", "b"]
You may want to tweak the above to somehow append the number of occurrences of each value.