3

There is one table , and I want the unique values of table column data, like table row may have 4, 2 , 2, 4,5 , 4. So it should return array like this data = [ 2 , 4 , 5 ]

I am able to achieve this using jquery as below link

http://jsbin.com/ojeroc/5/edit#source

But data should come in ascending order So I can use this array in another function.

$(document).ready(function(){
    console.log("document is ready");          
    var items=[], options=[];
    console.log(items);
    console.log(options);
    //Iterate all td's in second column
    $('#dataTable tr  td').each( function(){
    //console.log("Inside tr data");                                                                                                         
       //add item to array
       items.push( $(this).text() );       
      // console.log($(this).text());
    });
    //restrict array to unique items
    var items = $.unique( items );
    alert(items);
});

2 Answers 2

2
function sortNumber(a,b)
{
      return a - b;
}

var n = ["10", "5", "40", "25", "100", "1"];
document.write(n.sort(sortNumber));

would create this output:

1,5,10,25,40,100

You could also wrap it in an anonymous function

n.sort(function(a,b){return a-b;})

Which would be faster, but if you need to use it over and over again, I would stick with the function.

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

1 Comment

Hope it was helpful for you ;-)
1

You can use Array.sort() method to sort array items:

var sortedItems = $.unique( items ).sort(function(a, b) {
    return a - b;
});

The function passed as parameter is used to compare two items in the array. It receives two elements.

The sorting is done by returning a negative/positive/zero number. To compare numbers, you can then simply substract b from a.

DEMO

3 Comments

Thanks, I want to retrieve minimum and maximum values of the sorted array , can that be done?
@Wazdesign If you think for a second, you will see it is easy.
After the sort, sortedItems[0] will get you the min and sortedItems[sortedItems.length-1] the max.

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.