0

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
}   
hellzone
  • 5,393
  • 25
  • 82
  • 148
  • 2
    What would a “unique array” look like? – Ry- Feb 07 '17 at 14:07
  • 1
    *"...and I want to compare with this id value."* Okay. That seems like a good place ot start. Where are you stuck? What has your research shown you? What has [searching](/help/searching) turned up? – T.J. Crowder Feb 07 '17 at 14:09
  • @Ryan There must be no student which has same id value. – hellzone Feb 07 '17 at 14:13
  • @hellzone: So the original can have students with the same id value? Do they have other properties? If so, how do you decide which one you want to keep? – Ry- Feb 07 '17 at 14:14
  • @T.J.Crowder Actually I thought that Javascript can have an interface like Set in Java. – hellzone Feb 07 '17 at 14:14
  • @Ryan I didn't specified so It doesn't matter. – hellzone Feb 07 '17 at 14:15
  • @hellzone: Yes, JavaScript has a `Set` type as of ES6. https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Set – Ry- Feb 07 '17 at 14:16

4 Answers4

2

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);
Vladu Ionut
  • 8,075
  • 1
  • 19
  • 30
0

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
Ry-
  • 218,210
  • 55
  • 464
  • 476
Lyubomir
  • 19,615
  • 6
  • 55
  • 69
0
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
Sagar V
  • 12,158
  • 7
  • 41
  • 68
-1

If you have underscore, you can use the following

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

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

mdsAyubi
  • 1,225
  • 9
  • 9
  • What if OP doesn't use underscore? OP didn't tag it so would be better if it was a plain JS answer. – putvande Feb 07 '17 at 14:48