FlyingCat
FlyingCat

Reputation: 14270

How to get unique data from rows in javascript

I am trying to get the unique data out of the rows.

My data

name  title
tim    1
tim    1
tim    2
tim    3
time   3
jenny  5
jenny  5
jenny  6
jenny  7

My goal is to display my table using javascript to show

tim    1
tim    2
time   3
jenny  5
jenny  6
jenny  7

I know it's easy to change the data structure or the way to select the data but I don't have the access to the DB so I need to figure out in the javascript

my first step is to push all the unique title to my peopleArray:

1
2
3
5
6
7

The codes I have tried.

 for(var a=0; a<results.length; a++){
        if(results[(a+1)]){
             if(a==0 || results[a].title != results[(a+1)].title){

                peopleArray.push(results[(a)].title)
             }
         }
      }

My codes don't really work and I am stocked here. Anyone has tips for this? Thanks a lot!

Upvotes: 0

Views: 154

Answers (3)

Brian Cray
Brian Cray

Reputation: 1275

If it's already sorted like you have in your question then you can use Array.filter():

data = data.filter(function (d, i) {
    var next = data[i+1] || {name: '', title: ''};
    return d.name != next.name || d.title != next.title;
});

If it's not sorted yet as you have in your question, do this first:

data = data.sort(function (a, b) {
    return a.name < b.name ? -1 : a.name == b.name ? 0 : 1;
});

Upvotes: 1

Ian
Ian

Reputation: 50903

For something that does not require the list to be sorted, you can use something like this:

http://jsfiddle.net/4dvfq/1/

var results = [{"name": "tim", "title": "1"},
               {"name": "jenny", "title": "2"},
               {"name": "tim", "title": "1"},
               {"name": "jenny", "title": "1"}];
// Should return "tim 1", "jenny 2", "jenny 1" items

function getUniques(arr) {
    var i = 0;
    var len = arr.length;
    var found = {};
    var ret = [];

    for (; i < len; i++) {
        var cur = arr[i];
        var name = cur.name;
        var title = cur.title;
        var name_title = name + title;

        if (!(name_title in found)) {
            ret.push(cur);
            found[name_title] = 1;
        }
    }
    return ret;
}

console.log(getUniques(results));

Upvotes: 1

user1726343
user1726343

Reputation:

function uniquify(results) {    
    var peopleArray = [];
    for (var a = 0; a < results.length; a++) {
        if (peopleArray.indexOf(JSON.stringify(results[a])) == -1) {
            peopleArray.push(JSON.stringify(results[a]));
        }
    }
    return peopleArray.map(function(val) {
        return JSON.parse(val);
    });
}

This works regardless of sort order and is flexible enough to be used with other schema. Here is a demonstration that uses your data: http://jsfiddle.net/w4cKg/

Upvotes: 0

Related Questions