简体   繁体   English

使用 jQuery 和 Javascript 的数组中的唯一项

[英]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:我有一系列项目,其中有一个重复出现的 id,因此出于说明目的,请考虑:

[
    {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.我想我需要 2 个 for 循环,但不确定第一个如何获得“唯一”名称。

Is there something in jQuery i can use that can solve.我可以使用 jQuery 中的某些东西可以解决。

Array.prototype.reduce() : 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));

You can do it with the help of underscore library _.unique function.您可以借助下划线库 _.unique 函数来完成。

First we need to convert the arrary from array of objects, to array of strings, by using JavaScript map function.首先,我们需要使用 JavaScript 映射函数将数组从对象数组转换为字符串数组。

After that, we using _.unique to get only unique strings.之后,我们使用 _.unique 来获取唯一的字符串。

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) http://underscorejs.org/#uniq(_.uniq和 _.unique 是一样的)

Try utilizing $.each()尝试使用$.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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM