Question

Javascript (visual studio code) e.g items = [{colour: "red", name: "A", quantity: 1},{ colour: "yellow", name:...

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.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

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);

Add a comment
Know the answer?
Add Answer to:
Javascript (visual studio code) e.g items = [{colour: "red", name: "A", quantity: 1},{ colour: "yellow", name:...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT