hellzone
hellzone

Reputation: 5236

How to create a unique array which has objects as elements?

I have an array of students and I want to create an unique array of this students. Each student has a unique id value and I want to compare with this id value.

Here is a Student object;

{
    "id" = "3232aab1",
    //some other properties
}   

Upvotes: 0

Views: 76

Answers (4)

mdsAyubi
mdsAyubi

Reputation: 1245

If you have underscore, you can use the following

ES6 _.uniq(Students, student=>student.id)

ES5 _.uniq(Students, function(student){return student.id;})

Upvotes: -1

Lyubomir
Lyubomir

Reputation: 20027

I'd probably take an approach similar to this...

class Students extends Map {
    set(key, value) {
        if (this.has(key)) { throw new Error('Student already there'); }
        return super.set(key, value);
    }
}


const students = new Students();

students.set(1, { name: 'Peter' });

console.log(students.get(1));

// students.set(1, { name: 'Gregor' }); this throws

Upvotes: 0

Sagar V
Sagar V

Reputation: 12478

var a=[];
a.push({id:1,name:"something"});
// repeat similar;

To access an id

a[index].id;

Sample code to search

var elem = 1; // id to be searched
//loop
for(var i=0; i<a.length; i++){
  if(elem == a[i].id){
    break;
  }
}
// now a[i] will return the required data {id:1,name:"something"}
// a[i].id = > 1 and a[i].name => something

Upvotes: 0

Vladu Ionut
Vladu Ionut

Reputation: 8183

var Students =[
{
    "id" : "3232aab1"  //some other properties
} ,
{
    "id" : "3232aab1"  //some other properties
}, 
{
    "id" : "3232aab2"  //some other properties
} ,
{
    "id" : "3232aab3"  //some other properties
} ,
{
    "id" : "3232aab2"  //some other properties
} ];

var tmpObj = {};
var uniqArray = Students.reduce(function(acc,curr){
  if (!tmpObj[curr.id]){
    tmpObj[curr.id] = true;
    acc.push(curr)
  }
  return acc;
},[]);
console.log(uniqArray);

Upvotes: 2

Related Questions