Split string then merge and remove duplicate value in array - javascript

I have an API and retrieve the data using jQuery.JSON. I use split to split the locations by "|". And now I'm trying to merge arrays that I've split using each in jQuery and remove the duplicates. I already tried concat. Is there a array_merge then array_filter function for javascript/jquery?
Here is my sample code below.
jQuery(document).ready(function($) {
let get_json = 'https://boards-api.greenhouse.io/v1/boards/frequence/departments/';
$.getJSON(get_json, function(data) {
let dept_arr = new Array();
let arr = new Array();
let i = 0;
$.each(data.departments, function(key, value) {
if (value.jobs.length > 0) {
$.each(value.jobs, function(key, value) {
dept_arr[i] = (value.location.name.split('|'));
i++;
});
}
});
console.log(dept_arr);
});
});

You need to loop over all the elements in the array returned by split(). And the easiest way to get rid of duplicates is with a Set.
jQuery(document).ready(function($) {
let get_json = 'https://boards-api.greenhouse.io/v1/boards/frequence/departments/';
$.getJSON(get_json, function(data) {
let dept_set = new Set();
$.each(data.departments, function(key, dept) {
$.each(dept.jobs, function(key, job) {
let locations = job.location.name.split('|');
$.each(locations, (i, loc) => dept_set.add(loc));
});
});
let dept_arr = [...dept_set]; // convert set to array
console.log(dept_arr);
});
});

Related

Jquery - get the name of an array item in an array

How do you reference the name of an array within an array?
var jon_count = [0,6,7,9]
var sue_count = [9,7,6,8]
var rob_count = [7,8,6,3]
var name_list = {jon_count, sue_count, rob_count}
I'm trying to get the name of each variable within the "name_list" not the values of each item.
$.each(name_list, function (index, value) {
$.each(value, function(ind, obj) {
console.log(value[ind]);
});
});
I know that's garbage, I want to see:
jon_countsue_countrob_count
But I keep getting the numbers.
You can just use the index variable:
$.each(name_list, function (index, value) {
alert(index);
});
Here is a fiddle.
i think you need this:
var name_list = {jon_count:"item 1", sue_count:"item 2", rob_count:"item 3"}
var keys = Object.keys(name_list)
keys.forEach((item) => {
console.log(item)
})

How to compare two array objects and remove matched objects from one array object

My Code Scenario is:
var Employees= [{name:"Ram",htno:1245},{name:"mohan",htno:1246},
{name:"madhu",htno:1247},{name:"ranga",htno:1248}]
var seletedEmployees= [{name:"mohan"},{name:"ranga"}];
var employeesdataAfterremoveSelected = [?];
You can store selected employees names in an array and then filter Employees array and check if employee's name is in this array:
var employees= [{name:"Ram",htno:1245},{name:"mohan",htno:1246},{name:"madhu",htno:1247},{name:"ranga",htno:1248}]
var selectedEmployees= ["mohan","ranga"];
var result = employees.filter(emp => selectedEmployees.includes(emp.name));
console.log(result);
To programatically get array of strings instead array of objects, you can use map:
var seletedEmployees= [{name:"mohan"},{name:"ranga"}].map(emp => emp.name);
From the code you have given above i think this might work
$.each(student, function(key, value){
if(matchedvalues.indexOf(value.name) < 0)
{
employeesdataAfterremoveSelected.push(value.name);
}
})
Here is a one liner, decomposed to explain :
// Start by filtering the first array on a condition.
employeesdataAfterremoveSelected = Employees.filter(
// Map the array of selected employees to only return the name
e => seletedEmployees.map(_e => _e.name)
// use the includes function to check if the name is in the array
.includes(e.name)
);
In one line :
employeesdataAfterremoveSelected = Employees.filter(e => seletedEmployees.map(_e => _e.name).includes(e.name));
You can use the filter method, something like below (not tested)
var Employees = [{name:"Ram",htno:1245}, {name:"mohan",htno:1246}]
var SelectedEmployess = [{name:"Ram",htno:1245}]
// filter the items from the invalid list, out of the complete list
var employeesdataAfterremoveSelected = Employees.filter((item.name) => {
return !SelectedEmployess.has(item.name);
})
// get a Set of the distinct, valid items
var validItems = new Set(employeesdataAfterremoveSelected);
You can try this:
var Employees = [{name:"Ram",htno:1245},{name:"mohan",htno:1246},
{name:"madhu",htno:1247},{name:"ranga",htno:1248}]
var seletedEmployees = [{name:"mohan"},{name:"ranga"}];
var employeesdataAfterremoveSelected = Employees.filter(name => {
return (name.name !== seletedEmployees[0].name && name.name !== seletedEmployees[1].name)
})
console.log(employeesdataAfterremoveSelected)
var Employees= [{name:"Ram",htno:1245},{name:"mohan",htno:1246},
{name:"madhu",htno:1247},{name:"ranga",htno:1248}]
var seletedEmployees= [{name:"mohan"},{name:"ranga"}];
var employeesdataAfterremoveSelected = Employees.filter(function(val,index) { console.log(val.name)
return !(seletedEmployees.map(function(e) { return e.name; }).indexOf(val.name));
});

How to get records from object without knowing keyname?

I am struggling with the following:
I have a JSON feed with my data (https://api.myjson.com/bins/1sz7s). I iterate through all ReportItems in this object through javascript / jquery.
Problem I am having is I want to fetch 'records' that contain a specific value, but without knowing the key's name. Basically some kind of if_exists(ID):
$.each(tabledata.ReportItems, function (key, val){
var ID = "value";
if (ID in ReportItems) {
alert("Found!");
};
It's easy when you know the keyname:
$.each(tabledata.ReportItems, function (key, val){
var ID = "value";
if (ID == val.keyname) {
alert("Found!");
};
I guess this is what you are asking for:
var a = {"ReportItems":[{"Id":"cf92aefb-b857-49ce-b568-722329377e5d","CampaignId":"384f5c87-f8c7-43a6-9deb-76340dcf4cd4","CompanyId":"3ae13b97-7a09-4342-8953-c1d5a55687db","Name":"Item_7699","Price":1577.0,"Enabled":true,"Start":"2015-06-03T16:55:27.1388252+02:00","End":"2015-06-08T16:55:27.1388252","PublicationId":"19031fa7-2288-4466-94d6-6909d2ed2aa1","MediaId":"91089a91-a4d3-436a-b853-9370972006f3","ItemType":1,"DateStatistics":[{"Date":"2015-06-03T16:55:27.1388252","ScanCount":1138,"ResponseCount":8530},{"Date":"2015-06-04T16:55:27.1388252","ScanCount":4429,"ResponseCount":3556},{"Date":"2015-06-05T16:55:27.1388252","ScanCount":9822,"ResponseCount":121},{"Date":"2015-06-06T16:55:27.1388252","ScanCount":3791,"ResponseCount":3569},{"Date":"2015-06-07T16:55:27.1388252","ScanCount":7275,"ResponseCount":1922},{"Date":"2015-06-08T16:55:27.1388252","ScanCount":7243,"ResponseCount":141}]},{"Id":"47de9aaa-8424-4461-ba72-ae2922777650","CampaignId":"384f5c87-f8c7-43a6-9deb-76340dcf4cd4","CompanyId":"50ede412-4eb0-429b-8d73-a1bfef41ebbc","Name":"Item_7699","Price":1577.0,"Enabled":true,"Start":"2015-06-03T16:55:27.1418263+02:00","End":"2015-06-08T16:55:27.1418263","PublicationId":"19031fa7-2288-4466-94d6-6909d2ed2aa1","MediaId":"91089a91-a4d3-436a-b853-9370972006f3","ItemType":1,"DateStatistics":[{"Date":"2015-06-03T16:55:27.1418263","ScanCount":1138,"ResponseCount":8530},{"Date":"2015-06-04T16:55:27.1418263","ScanCount":4429,"ResponseCount":3556},{"Date":"2015-06-05T16:55:27.1418263","ScanCount":9822,"ResponseCount":121},{"Date":"2015-06-06T16:55:27.1418263","ScanCount":3791,"ResponseCount":3569},{"Date":"2015-06-07T16:55:27.1418263","ScanCount":7275,"ResponseCount":1922},{"Date":"2015-06-08T16:55:27.1418263","ScanCount":7243,"ResponseCount":141}]}],"Companies":{"8df135f4-db42-486c-8d8c-fbbdd561c25e":"Phillips","47d946e3-56db-4bc7-8472-3809eb48506d":"Bauknecht","3ae13b97-7a09-4342-8953-c1d5a55687db":"Capitol","fb017214-dbc1-4b71-8080-4f9b530f4b49":"Bosch","50ede412-4eb0-429b-8d73-a1bfef41ebbc":"LG Corp"},"Campaigns":{"0950aea6-69f3-42c1-99e5-25342c6262ae":"Campagne A","384f5c87-f8c7-43a6-9deb-76340dcf4cd4":"Campagne B"},"Media":[{"Id":"5999703b-a12e-49ad-b054-46875b88ff3a","Name":"Krant","Publications":{"e63f1212-5a21-4546-861c-640007989f08":"Telegraaf","13c3caa6-fcb8-4247-9cf7-8bfe0a0b5056":"Metro","3ddb7f5d-5e28-48ba-8345-5c4e3c7f76c0":"De Volkskrant"}},{"Id":"91089a91-a4d3-436a-b853-9370972006f3","Name":"Televisie","Publications":{"2eac3fd8-b8ed-47b7-8f14-664c3c55425a":"Rtl 4","defab016-d28e-4cf4-b814-0002169cf4cb":"MTV","19031fa7-2288-4466-94d6-6909d2ed2aa1":"Discovery Channel"}},{"Id":"e8610914-52b2-4b38-bc91-bf1bd6d63035","Name":"Radio","Publications":{"3585993c-56b4-4f7d-ac9c-a325eae2e78f":"SkyRadio","15e40597-e479-4a8f-9b25-f39ba90f2c19":"Radio 538","638e1141-f21c-42f1-acd1-652d265c32a1":"Slam FM"}}]};
var result = [];
$.each(a.ReportItems[0], function(k,v){
var specificValue = "cf92aefb-b857-49ce-b568-722329377e5d";
if(v == specificValue){
result[k]=v;
}
})
console.log(result);
Since you don't already know keynames, you can iterate through val properties to match value
$.each(tabledata.ReportItems, function (key, val){
var ID = "value";
for (var keyname in val) {
if (ID == val[keyname]) {
alert("Found!");
}
}
});

how to get length of json encoded array in javascript?

I have a json encoded array like this:
{
"ar0":"{\"start\":{\"lat\":22.9939202,\"lng\":72.50009499999999},\"end\":{\"lat\":23.0394491,\"lng\":72.51248850000002},\"waypoints\":[[23.0316834,72.4779436]]}",
"ar1":"{\"start\":{\"lat\":22.9999061,\"lng\":72.65318300000001},\"end\":{\"lat\":23.0420584,\"lng\":72.67145549999998},\"waypoints\":[[23.02237,72.6500747]]}",
"ar2":"{\"start\":{\"lat\":23.0394491,\"lng\":72.51248850000002},\"end\":{\"lat\":22.9999061,\"lng\":72.65318300000001},\"waypoints\":[[23.0016629,72.58898380000005]]}"
}
my quetion is :
(1) How to find length of this array? //here it is 3
(2) How to use it's value?
//for example:for as0 the value is {\"start\":{\"lat\":22.9939202,\"lng\":72.50009499999999},\"end\":{\"lat\":23.0394491,\"lng\":72.51248850000002},\"waypoints\":[[23.0316834,72.4779436]]}
javascript code where i use upper things :
function setroute(os)
{
var wp = [];
for(var i=0;i<os.waypoints.length;i++)
wp[i] = {'location': new google.maps.LatLng(os.waypoints[i][0], os.waypoints[i][1]),'stopover':false }
ser.route({'origin':new google.maps.LatLng(os.start.lat,os.start.lng),
'destination':new google.maps.LatLng(os.end.lat,os.end.lng),
'waypoints': wp,
'travelMode': google.maps.DirectionsTravelMode.DRIVING},function(res,sts) {
if(sts=='OK')ren.setDirections(res);
})
}
function fetchdata()
{
var jax = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
jax.open('POST','process.php');
jax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
jax.send('command=fetch')
jax.onreadystatechange = function(){ if(jax.readyState==4) {
alert(JSON.parse(jax.responseText).ar0);
try {
console.log(jax.responseText);
//it is not work
for(var i=0;i<JSON.parse(jax.responseText).length;i++)
{
setroute( eval('(' + jax.responseText + ')') );
}
}
catch(e){ alert(e); }
}}
}
Your JSON is not an array, but an object. If you want it to be an array, it should be something like this:
[
"{\"start\":{\"lat\":22.9939202,\"lng\":72.50009499999999},\"end\":{\"lat\":23.0394491,\"lng\":72.51248850000002},\"waypoints\":[[23.0316834,72.4779436]]}",
"{\"start\":{\"lat\":22.9999061,\"lng\":72.65318300000001},\"end\":{\"lat\":23.0420584,\"lng\":72.67145549999998},\"waypoints\":[[23.02237,72.6500747]]}",
"{\"start\":{\"lat\":23.0394491,\"lng\":72.51248850000002},\"end\":{\"lat\":22.9999061,\"lng\":72.65318300000001},\"waypoints\":[[23.0016629,72.58898380000005]]}"
]
Then, you can get a javascript array as follows:
var array = JSON.parse(jax.responseText);
And access values as follows:
array[0]
array.length
EDIT: In order to have a real JSON array with the PHP json_encode method, see this related question.
With this modification you will be able to use all the possibilities of JS array without workaround.
Objects in JavaScript don't have a .length property like Arrays do.
In ES5 you can do: Object.keys({}).length; // 0
The other solution would be to loop over all the properties of your object with a for .. in loop and count.
You can use the following code. It will produce your desired output 3
var test = {
"ar0":"{\"start\":{\"lat\":22.9939202,\"lng\":72.50009499999999},\"end\":{\"lat\":23.0394491,\"lng\":72.51248850000002},\"waypoints\":[[23.0316834,72.4779436]]}",
"ar1":"{\"start\":{\"lat\":22.9999061,\"lng\":72.65318300000001},\"end\":{\"lat\":23.0420584,\"lng\":72.67145549999998},\"waypoints\":[[23.02237,72.6500747]]}",
"ar2":"{\"start\":{\"lat\":23.0394491,\"lng\":72.51248850000002},\"end\":{\"lat\":22.9999061,\"lng\":72.65318300000001},\"waypoints\":[[23.0016629,72.58898380000005]]}"
}
var getLength = function(obj) {
var i = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)){
i++;
}
}
return i;
};
console.log(getLength(test));
For your first question, you should use Object.keys(item).length
To get the values of your object, you should iterate over it with a for loop:
for(var key in item)
{
var val = item[key];
}
var count = 0;
Object.keys(json).forEach(function (key) {
count++;
alert(json[key].start.lat);
});
alert(count);
Using jQuery
$(json).each(function() { count++; alert(this.start.lat); });
alert(count);

cant save all the locations values into my array

I am requesting to twitter to get all the locations of my users but then when i try to put them into my array all my objects get the same location(the last location of $.each).
its like i cant to loop through all the array values because of the each.function.i also tried putting outside the each.loop but same thing happens. Can someone tell me how to solve this.thanks!
function lookup_locations(user_ids){
$.getJSON("http://api.twitter.com/1/users/lookup.json?user_id="+user_ids+"&callback=?",
function(data){
$.each(data, function(i, item){
var location=item.location; console.log(location);
for(var i = 0; i < array.length;i++) {
array[i].location = location;
}
});
console.log(array);
});//get.json
}//lookup function
Try removing the for loop; i is being incremented by the $.each so you don't need it.
var array = [];
$.each(data, function(i, item) {
var location = item.location;
array[i].location = location;
});

Categories

Resources