score:0

the text field should map to this zone field in the array. In case of duplicate values, such as in this case, I want only 1 text element to be appended. Is the Array.filter function an option? If yes, then where do I use it?

Actually if you want to return only 1 object matching this zone from your array, you can't use .filetr()as it will return alll the elements that have the same zone.

You can use Array#find() it will return only the first object that pass the condition:

The find() method returns the value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned.

This is how should be your code:

var myObj = dataVal.find(function(item) {
  return item.zone === "Bandra-Pillers";
});

Demo:

var dataVal = [{
    "count": 1267,
    "path": 1,
    "zone": "Bandra-Pillers"
  },
  {
    "count": 697,
    "path": 2,
    "zone": "Bandra-Pillers"
  },
  {
    "count": 560,
    "path": 3,
    "zone": "Bandra-Pillers"
  }
];

var myObj = dataVal.find(function(item) {
  return item.zone === "Bandra-Pillers";
});

console.log(myObj);

Edit:

You can call it in the callback function of .html() like this:

var textG = g.append("g")
     .append("text")
     .html(function(d) {
         return dataVal.filter(function(item){
              return item.zone === zone; //Pass zone variable here
         })[0].data.zone;
});

Related Query