Get Unique Results from JSON Array Using Jquery

Get unique results from JSON array using jQuery

I don't know how your products array is built up (so my example might need some modification according to your needs), but you could write a little piece of code that will first collect your unique categories into a new array:

var categories = [];

$.each(catalog.products, function(index, value) {
if ($.inArray(value.category, categories) === -1) {
categories.push(value.category);
}
});

jsFiddle Demo

categories will hold the unique categories you need, you can use it to build your HTML from that (be careful with the IDs of those li elements though, remember that IDs cannot be duplicate, you might give them a little prefix).

how to get distinct values from json in jquery

I'm not sure how performant this will be, but basically I'm using an object as a key/value dictionary. I haven't tested this, but this should be sorted in the loop.

function(data) {
var birthDates = {};
var param = "birthDate"
$.each(data.people, function() {
if (!birthDates[this[param]])
birthDates[this[param]] = [];
birthDates[this[param]].push(this);
});

for(var d in birthDates) {
// add d to array here
// or do something with d
// birthDates[d] is the array of people
}
}

Selecting distinct values from a JSON

I would use one Object and one Array, if you want to save some cycle:

var lookup = {};
var items = json.DATA;
var result = [];

for (var item, i = 0; item = items[i++];) {
var name = item.name;

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

In this way you're basically avoiding the indexOf / inArray call, and you will get an Array that can be iterate quicker than iterating object's properties – also because in the second case you need to check hasOwnProperty.

Of course if you're fine with just an Object you can avoid the check and the result.push at all, and in case get the array using Object.keys(lookup), but it won't be faster than that.

How to foreach unique value from a json array

Try this one.

you can use .map()

$(document).ready(function(){
var jsonstirn = '[{"capacity":"4Seater","carname":"car1","price":"83"},{"capacity":"4Seater","carname":"i10","price":"83"},{"capacity":"4Seater","carname":"i20","price":"83"},{"capacity":"8Seater","carname":"car3","price":"83"}]';
var jsonarray = JSON.parse(jsonstirn);

var capacity_array = jsonarray.map(function(obj) { return obj.capacity; });
capacity_array = capacity_array.filter(function(v,i) { return capacity_array.indexOf(v) == i; });

var capacity_val = '';
$.each(capacity_array,function(i,item){
capacity_val+='<option value="'+item+'">'+item+'</option>';
})

$('#select1').html(capacity_val);
});

Applying a conditional filter to get unique values on JSON array

You can do:

let result = [...new Set(                                              //Use new Set to get unique values
arr.filter(o=>o.Session_type === search && o.Interest_area.trim() !== '' ) //Use filter to filter the Session_type and Interest_area is not blank
.reduce((c,v)=>c.concat(v.Interest_area.split(',')),[])) //Use reduce and concat to flatten the array
.map(o=>o.trim()) //Use map to trim the values
]

Here is a snippet:

let arr=[{"Event_code":"AB-001","Interest_area":"Arts and Education","Start_time":"9:00 AM","End_time":"3:00 PM","Session_type":"Course information session"},{"Event_code":"AB-002","Interest_area":"Arts and Education","Start_time":"12:30 PM","End_time":"1:00 PM","Session_type":"Course information session"},{"Event_code":"AB-003","Interest_area":"","Start_time":"9:00 AM","End_time":"3:00 PM","Session_type":"Course information session"},{"Event_code":"AB-004","Interest_area":"Business","Start_time":"10:30 AM","End_time":"11:00 AM","Session_type":"Course information session"},{"Event_code":"AB-005","Interest_area":"General Interest","Start_time":"9:30 AM","End_time":"1:30 PM","Session_type":"Experience"},{"Event_code":"AB-006","Interest_area":"Environment   ,    Business       ","Start_time":"11:00 AM","End_time":"11:30 AM","Session_type":"Course information session"}];
let search = 'Course information session';let result = [...new Set(arr.filter(o=>o.Session_type === search && o.Interest_area.trim() !== '' ).reduce((c,v)=>c.concat(v.Interest_area.split(',')),[]).map(o=>o.trim()))]
console.log(result);

How to make a JSON array unique

Check the solution in the following SO question:

Get unique results from JSON array using jQuery

You'll have to iterate through your array and create a new array which contains unique values.

Get all unique values in a JavaScript array (remove duplicates)

With JavaScript 1.6 / ECMAScript 5 you can use the native filter method of an Array in the following way to get an array with unique values:

function onlyUnique(value, index, self) {
return self.indexOf(value) === index;
}

// usage example:
var a = ['a', 1, 'a', 2, '1'];
var unique = a.filter(onlyUnique);

console.log(unique); // ['a', 1, 2, '1']

JSON get unique random values from array to text input html and show a text when all values are shown

One way would be to keep a reference of the list (firstCouponOptions as in the below mentioned code) and each time a random value is fetched from firstCouponOptions show it in the "text box" and remove the value from the firstCouponOptions list at the same time. When it is empty, show "No coupon" message.

const options = [  { "country": "First", "coupon": ["1", "10", "11"] },  { "country": "Second", "coupon": "2" },  { "country": "third", "coupon": "3" },  { "country": "fourth", "coupon": "4" },  { "country": "fifth", "coupon": "5" }];
function getRandomValueFromList(list) { const randomeIndex = Math.floor(Math.random() * (list.length)); return list[randomeIndex];}
$(function() { const firstCouponOptions = options[0].coupon; options.forEach((value) => { $('#sel') .append('<option value="' + value.coupon + '">' + value.country + '</option>'); });
$('#sel').change(function() { let str = $("#sel").val(); if ($("#sel option:selected").text() === 'First') { if (firstCouponOptions.length) { str = getRandomValueFromList(firstCouponOptions); firstCouponOptions.splice(firstCouponOptions.indexOf(str), 1); } else { str = "No Coupon"; } } console.log(str); $("#txtName").val(str); });});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><select id="sel" class="form-control input-lg" data-live-search="true">  <option value="">-- Select Your Country--</option></select>
<input type="text" id="txtName" class="form-control input-lg" />


Related Topics



Leave a reply



Submit