Javascript (visual studio code)
e.g items = [{colour: "red", name: "A", quantity: 1},{ colour: "yellow", name: "B", quantity:2 },{ colour: "green", name: "C", quantity: 3 },{ colour: "white", name: "D", quantity: 4},{ colour: "grey", name: "E", quantity: 5 },{ colour: "blue", name: "D", quantity: 6}];
Exercise 2 Write a function that inputs an array of your items and returns the list of category values (i.e. [‘red’,’white’,..] for your chosen attribute. The returned array should not contain duplicates.
function getUniqueValues(obj,attribute) //As specified the
function takes two input given array of objects and an
attribute
{ // object
var iter=obj.values(); // This will return an iterator for the
array
var s=new Set(); // Using a Set for Unique values of specified
attribute
for(let elements of iter) // Traversing on each object using
iterator of array
{
s.add(elements[attribute]); // element will conatin the reference
to each object in array and add the attribute value to Set
's'
}
return [...s]; // A shortcut notation to get the values of Set in
an Array and return it
}
// Testing the above function
arr=[{colour: "red", name: "A", quantity: 1},
{colour: "yellow", name: "B", quantity:2},
{colour: "green", name: "C", quantity: 3},
{colour: "white", name: "D", quantity: 4},
{colour: "grey", name: "E", quantity: 5 },
{colour: "blue", name: "D", quantity: 6}];
var ar=getUniqueValues(arr,"quantity");
console.log(ar);
Javascript (visual studio code) e.g items = [{colour: "red", name: "A", quantity: 1},{ colour: "yellow", name:...