admin管理员组

文章数量:1315810

I have this type of JSON data

I have written the code to eliminate duplicate records in JQuery

function GetUniqueTablesCategory(Data) {
  var UniqueNames = $.unique(Data, function(d) {
    return d.TableName;
  });
  return UniqueNames;
}

But I am getting this error below, can anyone please help me out to eliminate this issue.

I have this type of JSON data

I have written the code to eliminate duplicate records in JQuery

function GetUniqueTablesCategory(Data) {
  var UniqueNames = $.unique(Data, function(d) {
    return d.TableName;
  });
  return UniqueNames;
}

But I am getting this error below, can anyone please help me out to eliminate this issue.

Share Improve this question edited May 13, 2015 at 9:03 Shaunak D 20.6k10 gold badges47 silver badges79 bronze badges asked May 13, 2015 at 7:28 G RG R 1371 gold badge3 silver badges12 bronze badges 5
  • 1 It throws an error because objects cannot be sorted. The $.unique() method is designed to be used with an array of DOMElements, see api.jquery./jQuery.unique – Rory McCrossan Commented May 13, 2015 at 7:31
  • Is this while running your code? It seems that you do not give an array as an argument. Did you convert the JSON into an array? – Sylvia Stuurman Commented May 13, 2015 at 7:31
  • Rory McCrossan , how I will achieve this without using $.unique() method, can you please share me any link. – G R Commented May 13, 2015 at 7:34
  • 1 You need to write your own logic to replicate it, via loops. – Rory McCrossan Commented May 13, 2015 at 7:39
  • I am going to write my own logic . , thanks . once I done will add in post . – G R Commented May 13, 2015 at 7:43
Add a ment  | 

4 Answers 4

Reset to default 3

You can write a one-liner using Set from ES6

let uniqueNames = [...new Set(Data.map(d => d.TableName))]

You can do that with a simple loop :

function GetUniqueTablesCategory(Data) {
  var UniqueNames = [];
  Data.forEach(function(value) {
      if (UniqueNames.indexOf(value.TableName) === -1) {
          UniqueNames.push(value.TableName);
      }
  });

  return UniqueNames ;
}

If underscore.js is acceptable, you can write your method like this:

function GetUniqueTablesCategory(data) {
  return _.uniq(_.map(data, function(d){return d.Name}));
}

fiddle

try something like this:

$(document).ready(function() {
	var lookup = {};
	var obj = [{'TableName': 'prop1','value5': 'prop3'},{ 'TableName': 'prop1','value5': 'prop3'}, {'TableName': 'prop3','value5': 'prop3'}];
	var array=[];
	for (var ob, i = 0; ob = obj[i++];) {
		  var name = ob.TableName;

		  if (!(name in lookup)) {
		    lookup[name] = 1;
		    array.push(name);
		  }
		}

	alert(JSON.stringify(array));
	
	});//submit click 
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>

you can find a similar thread here also.see

本文标签: javascriptHow to Get Distinct Values From Json Data without sortingStack Overflow