userMod2
userMod2

Reputation: 8960

Unique Items in Array using jQuery and Javascript

Have an issue (not overly complicated, however I just can't seem to think of a clear way to solve).

I have an array of items, in which there is a recurring id, so for illustrative purposes think:

[
    {name: "john", task: "dig"},
    {name: "john", task: "swim"},
    {name: "john", task: "eat"},
    {name: "paul", task: "dig"},
]

From this I want to create a table where the columns would be the name - so John and Paul, then underneath there would be the tasks.

I'm thinking I'd need 2 for loops however not sure how the first would just get the 'unique' names.

Is there something in jQuery i can use that can solve.

Upvotes: 1

Views: 72

Answers (3)

guest271314
guest271314

Reputation: 1

Try utilizing $.each()

var data = [{
  name: "john",
  task: "dig"
}, {
  name: "john",
  task: "swim"
}, {
  name: "john",
  task: "eat"
}, {
  name: "paul",
  task: "dig"
}];

$.each(data, function(key, value) {
  var fn = function(el) {
    return el.find("tbody").append($("<tr />", {
      "html": "<td>" + value.task + "</td>"
    }))
  }
  if (!$("table[name=" + value.name + "]").is("*")) {
    var elem = $("<table />", {
      "name": value.name,
      "html": "<tbody><th>" + value.name + "</th></tbody>"
    }).appendTo("body");
    fn(elem)
  } else {
    fn($("table[name=" + value.name + "]"))
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>

Upvotes: 0

Siguza
Siguza

Reputation: 23830

Array.prototype.reduce():

var arr = 
[
    {name: 'john', task: 'dig'},
    {name: 'john', task: 'swim'},
    {name: 'john', task: 'eat'},
    {name: 'paul', task: 'dig'},
];
var result = arr.reduce(function(table, element)
{
    if(!table[element.name])
    {
        table[element.name] = [];
    }
    table[element.name].push(element.task);
    return table;
}, {});
// For demo:
document.write(JSON.stringify(result));

Upvotes: 4

Aminadav Glickshtein
Aminadav Glickshtein

Reputation: 24590

You can do it with the help of underscore library _.unique function.

First we need to convert the arrary from array of objects, to array of strings, by using JavaScript map function.

After that, we using _.unique to get only unique strings.

x=[
{name: 'john', task: 'dig'},
{name: 'dani', task: 'didg'},
{name: 'john', task: 'diadg'},
{name: 'john', task: 'diasdg'},
];
x=x.map(function (i) {return i.name}) // ['john','dani','john','john']
x=_.unique(x)     //   ['john','dani']

http://underscorejs.org/#uniq (_.uniq and _.unique are the same)

Upvotes: 1

Related Questions