简体   繁体   English

具有唯一键的 javascript 和 es6 过滤器数组

[英]javascript and es6 filter array with unique key

I have a list in variable like:我有一个变量列表,例如:

var name_list = some_list

console.log(name_list)

Array[3]
   0: Object
       name: "Johny"
   1: Object
       name: "Monty"
   2: Object3:
      name: "Johny"

I want to get the list with non repetitive list.我想获得具有non repetitive列表的列表。 How can I do this ?我怎样才能做到这一点 ?

Update更新

I tried with this..我试过这个..

var unique_name = [ ...new Set(name_list.map(name => {
                return name.name
            }))]

It works fine but I want the object that are filtered unique according to name.它工作正常,但我希望根据名称过滤的object是唯一的。

Any idea ??任何想法 ??

reduce over the array keeping a lookup of previous entries to check against. reduce在数组上保持查找以前的条目以进行检查。

 const arr=[{name:"Johny"},{name:"Monty"},{name:"Johny"}]; function dedupeByKey(arr, key) { const tmp = {}; return arr.reduce((p, c) => { const k = c[key]; if (tmp[k]) return p; tmp[k] = true; return p.concat(c); }, []); } console.log(dedupeByKey(arr, 'name'));

Or you can filter using a similar approach:或者您可以使用类似的方法进行filter

 const arr=[{name:"Johny"},{name:"Monty"},{name:"Johny"}]; function dedupeByKey(arr, key) { const temp = arr.map(el => el[key]); return arr.filter((el, i) => temp.indexOf(el[key]) === i ); } console.log(dedupeByKey(arr, 'name'));

Another approach I don't see in here would be to use a Map我在这里看不到的另一种方法是使用Map

var name_list = [{name: "Johny"}, {name: "Monty"}, {name: "Johny"}];

// Make a mapping of name to object, then pullout objects.
var name_map = new Map(name_list.map(o => [o.name, o]));
var unique_names = [...name_map.values()];

Note, this will take the last object for each name instead of the first, but you could always do name_list.slice().reverse().map( instead of you need specifically the first object found.请注意,这将采用每个名称的最后一个对象而不是第一个对象,但是您始终可以执行name_list.slice().reverse().map(而不是专门需要找到的第一个对象。

Filter to keep only those elements which are the first occurrence of the name (in other words, whose index is the same as the index of the first occurrence):过滤以仅保留名称第一次出现的那些元素(换句话说,其索引与第一次出现的索引相同):

 var name_list = [{name: "Johny"}, {name: "Monty"}, {name: "Johny"}]; var filtered = name_list . filter( (elt, i, a) => i === a.findIndex( elt2 => elt.name === elt2.name ) ); document.getElementById('result').textContent = JSON.stringify(filtered);
 <pre id='result'></pre>

This might not be the fastest approach, but it could be the simplest.这可能不是最快的方法,但它可能是最简单的。

You can use this little distinctByProp( theArray, propertyName) function.您可以使用这个小distinctByProp( theArray, propertyName)函数。

I hope it helps我希望它有帮助

distinctByProp = (theArray, prop) => {
    let tempArray = [];
    let isFound = obj => tempArray.find( n => n[prop] === obj[prop]);
    theArray.forEach( current => !isFound(current) && tempArray.push(current));
    return tempArray;
}

Usage is like:用法如下:

let names_list = [{name: "Johny"}, {name: "Johnyh"}, {name: "Max"}, {name: "Monty"}, {name: "Johnyh"}, {name: "Max"}];

let distinct = distinctByProp(names_list, "name");

console.log(distinct);

I hope it helps我希望它有帮助

You could use Array#filter() .您可以使用Array#filter()

 var name_list = [{ name: "Johny" }, { name: "Monty" }, { name: "Johny" }], filtered = name_list.filter(a => { this.my = this.my || Object.create(null); if (!this.my[a.name]) { this.my[a.name] = true; return true; } }); document.write('<pre>' + JSON.stringify(filtered, 0, 4) + '</pre>');

This is my resumed form of this type of unique.这是我这种独特的简历形式。 Not only for one field but for all the root fields of the object.不仅针对一个字段,而且针对对象的所有根字段。

const unique = l => l.filter(
  (e1, i, a) => i === a.findIndex(
    e2 => Object.keys(e1)
      .map(x => e1[x] === e2[x])
      .reduce((x,y) => x && y)
  )
)

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

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