0

I have this for loop. It's console logging colors from the color fields in my json file. But there are duplicate colors.

This is my json code

var movies = [
  {
    "name": "Feugo",
    "outline": "Description about Hydrangea flowers.",
    "months": [
      "Jan",
      "Feb",
      "Mar",
      "Apr",
      "Nov",
      "Dec"
    ],
    "color": [
      "Orange",
      "Yellow"
    ],
    "type": [
      "Alstroemeria"
    ],
    "image": "alstroemeria-fuego_w300_h400.jpg",
    "id": 1
  },
  {
    "name": "Atlanta",
    "outline": "Description about Hydrangea flowers.",
    "months": [
      "Jan",
      "Feb",
      "Mar",
      "Apr",
      "Nov",
      "Dec"
    ],
    "color": [
      "Purple",
      "Yellow",
      "White"
    ],
    "type": [
      "Alstroemeria"
    ],
    "image": "alstroemeria-atlanta_w300_h400.jpg",
    "id": 2
  },

This is my for loop:

for (var i = 0; i < movies.length; i++) {
    var obj = movies[i];
    for (var j = 0; j < obj.color.length; j++) {
         console.log(obj.color[j]);
     }
 }

How do I only display one of each?

Thanks!

francdore
  • 165
  • 2
  • 16
  • Show your `json` also. – Manwal Feb 03 '15 at 12:17
  • Besides the logical: perhaps you want to do this on the server and limit the amount of data being send. One of each *per* movie or one of each color period? – Leon Feb 03 '15 at 12:17
  • possible duplicate of [Unique values in an array](http://stackoverflow.com/questions/1960473/unique-values-in-an-array) – Jivings Feb 03 '15 at 12:18
  • Sorry I don't know how to apply other solutions to my code as it looks different. I don't understand Javascript well enough. – francdore Feb 03 '15 at 12:28

2 Answers2

1

Many solutions for getting unique values involve setting object properties, and reading out those properties on completion.

A quick and dirty example reusing your example loop:

var colsObj = {};
for (var i = 0; i < movies.length; i++) {
    var obj = movies[i];
    for (var j = 0; j < obj.color.length; j++) {      
         colsObj[obj.color[j]] = 1;
     }
 }
var collarr = Object.keys(colsObj);
console.log(collarr); 

Example

The setting to 1 is just a place holder, you could set it to undefined or any other value, as long as the property is created. The properties are set on the dummy object colsObj. Object.keys gives back an array of the object's direct enumerable properties.

Me.Name
  • 12,259
  • 3
  • 31
  • 48
0

You could insert each item in to a Set object which guarentees that each item is unique then iterate over the set:

var colourSet = new Set();
for (var j = 0; j < obj.color.length; j++) {
  colourSet.add(obj.color[j]);
}
for (let colour of colourSet) console.log(colour);

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set for more informations on the Set object.