在数组对象中搜索唯一属性 [英] searching for unique properties in the array object

查看:46
本文介绍了在数组对象中搜索唯一属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

     var name = [ {
 firstN: 'Dave',
 lastN: 'Mike',
 fullName: 'Dave Mike
 },
 { 
 firstN: 'Dave',
 lastN: 'Pence',
 fullName: 'Dave Pence'
 },
  { 
 firstN: 'Tom',
 lastN: 'Pence',
 fullName: 'Tom Pence'
 }, { 
 firstN: 'Meagher',
 lastN: 'Pence',
 fullName: 'Meagher Pence'
 }, { 
 firstN: 'Surv',
 lastN: 'dyal',
 fullName: 'Surv dyal
 }
  ................and so on like 100s
 ]

因此,我想查找唯一的名称,以使名称仅出现一次

So I want to find unique names so that names occur only once

应该是戴夫·迈克和Surv Dyal

So my answer from above data sample should be Dave Mike and Surv Dyal

为此,我到目前为止只得到了

For this I have gotten only this far

var list =Object.keys(newList).map( function(key){

    var temp_firstName = newList[key].firstName + ','+ key;
    var temp_lastName = newList[key].lastName + ','+ key;
    console.log( temp_lastName,temp_firstName );

    return temp_lastName, temp_firstName;
});

console.log(list);
//console.log(newList);

}

推荐答案

array.map 是错误的方法,因为它是一对一的数组转换。您正在寻找的是一种可以修剪数组的方法,该数组可以是 array.filter array.reduce 以及记录您已经遇到过的名称的临时键值存储。

array.map is the wrong method to use since it's a 1-to-1 array transformation. What you're looking for is a method that can trim down an array, either array.filter or array.reduce and a temporary key-value store that records names you've already encountered.

const names = [{
    firstN: 'Dave',
    lastN: 'Mike',
    fullName: 'Dave Mike'
  },
  {
    firstN: 'Dave',
    lastN: 'Pence',
    fullName: 'Dave Pence'
  },
  {
    firstN: 'Tom',
    lastN: 'Pence',
    fullName: 'Tom Pence'
  }, {
    firstN: 'Meagher',
    lastN: 'Pence',
    fullName: 'Meagher Pence'
  }, {
    firstN: 'Surv',
    lastN: 'dyal',
    fullName: 'Surv dyal'
  }
]

const fn = {};
const ln = {};

const uniqueNames = names.filter(name => {
  // Check if it already exists.
  const wasVisited = Boolean(fn[name.firstN]) || Boolean(ln[name.lastN]);

  // Record the visit:
  fn[name.firstN] = ln[name.lastN] = true;

  // return the verdict
  return !wasVisited;
});

console.log(uniqueNames)

这篇关于在数组对象中搜索唯一属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆