如何从对象数组Javascript中获取唯一值

时间:2018-07-26 11:18:41

标签: javascript arrays duplicates

所以我有一个如下的对象数组:

var array = [
    {name:"Joe", date:'2018-07-01', amt:250 },
    {name:"Mars", date:'2018-07-01', amt:250 },
    {name:"Joe", date:'2018-07-02', amt:250 },
    {name:"Saturn", date:'2018-07-01', amt:250 },
    {name:"Joe", date:'2018-07-02', amt:250 },
    {name:"Jupiter", date:'2018-07-01', amt:250 },
]

我想根据nameamountdate是否重复来过滤数据。 这个甚至不会过滤重复的名称。

var unique = array.filter((v, i, a) =>{ return a.indexOf(v) === i});

如何根据nameamountdate对此重复项进行过滤?

10 个答案:

答案 0 :(得分:5)

尝试使用此代码,它仅返回唯一的对象。

case Some(system: ActorSystem) =>




   Option(ActorSystemSetting.getActorSystem) match {
          case Some(system: ActorSystem) =>
            system.actorOf(Props[PaymentViaCreditDeletionActor]
              , name = "PaymentViaCreditDeletionActor")
          case None => log.debug("ActorSystem is null")
        }
}

请告诉我这是否不是您想要的东西。

答案 1 :(得分:2)

var array = [
    {name:"Joe", date:'2018-07-01', amt:250 },
    {name:"Mars", date:'2018-07-01', amt:250 },
    {name:"Joe", date:'2018-07-02', amt:250 },
    {name:"Saturn", date:'2018-07-01', amt:250 },
    {name:"Joe", date:'2018-07-02', amt:250 },
    {name:"Jupiter", date:'2018-07-01', amt:250 },
]

let answer = [];

array.forEach(x => {
  if(!answer.some(y => JSON.stringify(y) === JSON.stringify(x))){
    answer.push(x)
  }
})

console.log(answer)

替代解决方案。您可以使用Array#forEach,Array#some,JSON.stringify实现所需的目标

答案 2 :(得分:2)

您可以使用https://lodash.com/

如果您只需要一个值来唯一:

var express = require('express')
  , https = require('https')
  , fs = require('fs')
  , path = require('path');

var app = express();

var  bodyParser = require('body-parser');
const {actionssdk,Image,} = require('actions-on-google');
const app2 = actionssdk();

//to display in console
app.get('*' , function (req, res, next) {
    console.log('Request URL:', req.originalUrl)
    next();
});

//intents created in my dialogflow
app2.intent('favourite_Color',function (conv, {color})  {
    var luckyNumber = color.length;
    conv.close('This is our lucky number - ' + luckyNumber);
});

app2.intent('call',function (conv, {contacts})  {
    console.log(contacts);
    console.log("call intent is triggered");
   conv.close('You are trying depu to call this person - ' + contacts);

app.use(bodyParser.json(),app2).listen(3000);

var options = {
            key:fs.readFileSync(pathIncluded),
            cert:fs.readFileSync(pathIncluded)
};

//this is the port I am trying to listen
https.createServer(options, app).listen(xxx, function(){
    console.log('Express server listening on port ' + xxx);
});

如果您需要通过完整的对象删除唯一标识:

array = _.uniqWith(array, function(arrVal, othVal) {
    return arrVal.name == othVal.name || arrVal.date == othVal.date || arrVal.amt == othVal.amt;
}) 
console.log(array);

答案 3 :(得分:1)

给出您的原始数组:

var array = [
    {name:"Joe", date:'2018-07-01', amt:250 },
    {name:"Mars", date:'2018-07-01', amt:250 },
    {name:"Joe", date:'2018-07-02', amt:250 },
    {name:"Saturn", date:'2018-07-01', amt:250 },
    {name:"Joe", date:'2018-07-02', amt:250 },
    {name:"Jupiter", date:'2018-07-01', amt:250 }
];

您需要一个函数来确定要检查的标准,以使您的对象与其他对象具有可比性。

更新

这样的函数可能是一个hash function,您应该编写此函数来创建一个唯一的键来标识您的对象并相互比较。

如果用具有相同组成键的对象调用正确的哈希函数,则应返回相同的值。

在您的情况下,当两个对象的 name date amount 具有相同的值时,哈希函数应该返回相同的值。

因此您可以直接比较哈希值而不是对象。

在您要求的情况下,所有值都归过滤器所有,这是该函数的一个非常简单的示例,由于输出是可变的,因此不适合作为“散列”(应产生固定的长度值):

function objectHash (obj) {
    return Object.values(obj).reduce((a, b) => {
        a += b;
        return a;
    }, '');
}

现在,您现在可以轻松,正确地比较数组中的项目,以过滤重复项。

var arrayMap = array.reduce((acc, item) => {
    var hash = objectHash(item);
    if (typeof acc[hash] === 'undefined') {
        acc[hash] = Object.assign({}, item);
    }
    return acc;
}, {})

然后您有一个具有唯一键值的对象,并返回了唯一数组:

 var uniqueArray = Object.values(arrayMap);

现在您有了数据。

答案 4 :(得分:1)

此代码显示控制台中的重复项。如果要打印除重复项以外的所有内容,请将return true替换为return false,将return false替换为return true

var orders = [
    {name:"Joe", date:'2018-07-01', amt:250 },
    {name:"Mars", date:'2018-07-01', amt:250 },
    {name:"Joe", date:'2018-07-02', amt:250 },
    {name:"Saturn", date:'2018-07-01', amt:250 },
    {name:"Joe", date:'2018-07-02', amt:250 },
    {name:"Jupiter", date:'2018-07-01', amt:250 },
];

orders = orders.filter( (order, index) => {

  // iterate over the array to check for possible duplicates
  // iterating over the items we already checked isn't necessary so we start at index+1
  for( let i = index+1; i<orders.length; i++ ){
    if(
      orders[i].name === order.name
      && orders[i].date === order.date
      && orders[i].amt === order.amt
    ){
     // just logging this stuff so you can see what happens
     console.log( `${index} is a duplicate of ${i}` );
     // if a duplicate is found return true to the filter function
     return true; 
    }
  }
  // if no duplication is found return false to the filter function
  return false;
  
}); // end filter 

// log the result to the console
console.log(orders);

答案 5 :(得分:1)

具有Array.prototype.filterSet的解决方案:

 namespace foo {
     void bar(); // foo::bar() declared
 }

 // you can define it as this
 namespace foo {
     void bar() {}
}

// or this
void foo::bar() {}

// this does not work
using namespace foo;
void bar() {} // ::bar() is defined here not foo::bar()

答案 6 :(得分:1)

您的数组:

 var array = [
    {name:"Joe", date:'2018-07-01', amt:250 },
    {name:"Mars", date:'2018-07-01', amt:250 },
    {name:"Joe", date:'2018-07-02', amt:250 },
    {name:"Saturn", date:'2018-07-01', amt:250 },
    {name:"Joe", date:'2018-07-02', amt:250 },
    {name:"Jupiter", date:'2018-07-01', amt:250 },
]

只需尝试一下:

var unique = Array.from(new Set(array.map(JSON.stringify))).map(JSON.parse);

答案 7 :(得分:0)

这就是我要做的:

const array = [
    {name:"Joe", date:'2018-07-01', amt:250 },
    {name:"Mars", date:'2018-07-01', amt:250 },
    {name:"Joe", date:'2018-07-02', amt:250 },
    {name:"Saturn", date:'2018-07-01', amt:250 },
    {name:"Joe", date:'2018-07-02', amt:250 },
    {name:"Jupiter", date:'2018-07-01', amt:250 },
];

function uniqueBy(arr, key, $some = false) {
  if (key instanceof Array) {
    if ($some) {
      return key.reduce(uniqueBy, arr);
    } else {
      const fnUnique = (obj) =>
        key.reduce((a, k) => `${a}-${obj[k]}`, '');
      return Object.values(arr.reduce((a, v) => {
          const key = fnUnique(v)
          return a[key] === undefined ? (a[key] = v, a) : a;
      }, {}));
  }
}
return Object.values(arr.reduce((a, v) => (a[v[key]] === undefined ? (a[v[key]] = v, a) : a), {}));
}

// print unique objects based on the given fields
console.log(uniqueBy(array, ['name', 'date', 'amt']));

// print unique objects based on any unique value in any given fields
console.log(uniqueBy(array, ['name', 'date', 'amt'], true));

这仅关心给定的字段,因此,如果对象具有重复项但具有其他不感兴趣的属性,则得到的结果会更少。

true用作第三个参数会将字段本身视为唯一。因此,结果将只包含所有字段都是唯一的对象,因此由于数量相同,您最终只能得到一个元素。

答案 8 :(得分:0)

用于过滤具有名称的唯一ID的代码

{id: 555, name: "Sales", person: "Jordan" },
{id: 555, name: "Sales", person: "Bob" },
{id: 555, name: "Sales", person: "John" },
{id: 777, name: "Accounts Payable", person: "Rhoda" },
{id: 777, name: "Accounts Payable", person: "Harry" },
{id: 888, name: "IT", person: "Joe" },
{id: 888, name: "IT", person: "Jake" },
];
var unique = [];
var tempArr = [];
data.forEach((value, index) => {
    if (unique.indexOf(value.name) === -1) {
        unique.push(value.name);
        tempArr.push(value.id);
    }
});
console.log('Unique Ids', tempArr);

答案 9 :(得分:-1)

这可以通过过滤数组来要求,以便包括的唯一元素是原始数组中第一匹配条目(别名为a)与当前正在检查的元素相同的index。 :

let uniq = array.filter(({name, date, amount}, index, a) =>
               a.findIndex(e => name === e.name &&
                                date === e.date &&
                              amount === e.amount) === index);