1

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.

1
  • reduce would do the trick I guess... no loops needed Commented Sep 6, 2015 at 18:46

3 Answers 3

4

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));

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

1 Comment

Perfect - love how there's so many great functions available :)
1

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)

Comments

0

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>

Comments

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.