Compare two arrays get unique values javascript - javascript

So I have an object array called Banker and i have an array called remove_banker_id,
so in my code
remove_banker_id = [11, 99]. My banker object banker.id has 11 and 99 and i dont want to include them in my third array so how do i do tht?
My current code has this in my javascript file
$.each(data, function( index, banker ) {
$.each(lender_banker_id_array, function(index, banker_id) {
if(parseInt(banker_id) !== banker.id) {
banker_object
.append($('<option>', {value: banker.id, html: banker.name }))
.removeAttr('disabled');
}
})
});
So basically if any lender_banker_id_array is in banker object, do not append it. But with this code it is not working properly. How do i solve this

Try using the jquery utility function $.inArray()
http://api.jquery.com/jquery.inarray/
It returns the index of a value in an array. It returns -1 if the array does not contain the value.
$.each(data, function( index, banker ) {
if($.inArray(banker.id, lender_banker_id_array) == -1) {
banker_object.append($('<option>', {
value: banker.id,
html: banker.name
})).removeAttr('disabled');
}
});

Related

How to extract json, multiple value using jquery

Hello I have a json data like this
KLOBS {"SL_VEF_APPLIED_VS_BOL_R1_KLOBS":["0.00247320692497939","0.000008129750823137272"]}
KL15 {"SL_VEF_APPLIED_VS_BOL_R1_KL15":["0.01890831252229754","0.9008162336184189"]}
I'm already try extract json
$.get('url_request.php?' + $(this).serialize(), function(data) {
var obj = data;
$.each(obj, function(key, value) {
console.log(key);
console.log(value);
});
});
$.each(obj, function(key, value) {
console.log(key);
console.log(value);
});
And I get result
KLOBS
{"SL_VEF_APPLIED_VS_BOL_R1_KLOBS":["0.00247320692497939","0.000008129750823137272"]}
KL15
{"SL_VEF_APPLIED_VS_BOL_R1_KL15":["0.01890831252229754","0.9008162336184189"]}
I want to get result like this:-
KLOBS
0.00247320692497939
0.000008129750823137272
KL15
0.01890831252229754
0.9008162336184189
How to call json like this ??
I don't know call multiple value data in Json.
Please help me.
Try this
var arr = {
KLOBS: {
SL_VEF_APPLIED_VS_BOL_R1_KLOBS: [
"0.00247320692497939",
"0.000008129750823137272"
]
},
KL15: {
SL_VEF_APPLIED_VS_BOL_R1_KL15: ["0.01890831252229754", "0.9008162336184189"]
}
};
Object.keys(arr).forEach(function(key, value) {
console.log(key);
Object.keys(arr[key]).forEach(function(val) {
arr[key][val].forEach(function(data) {
console.log(data);
});
});
});
In general you could do the following:
var KLOBS = {"SL_VEF_APPLIED_VS_BOL_R1_KLOBS":
["0.00247320692497939","0.000008129750823137272"]}
values = Object.keys(KLOBS).map(x=>{
return KLOBS[x];
})
values.forEach(x=>x.forEach(y=>console.log(y)))
jsfiddle
Object.keys gives you an array of the keys in an object.
Since I do not know the structure in advance, I assume it better thinking of more than one key.
With the function map, a function is applied to each member of the array returned by Object.keys. This is used to extract the values.
The resulting structure is an array of arrays.
Therefore a double forEach is needed to display every entry of the structure.

Loop ONLY through a defined JSON object in a nested structure - JQUERY

I have the following json structure (I've made it shorter for simplify):
{
"employees":{"0":"Name1 Surname1", "1":"Name2 Surname2"},
"managers":{"0":"Name3 Surname3", "1":"Name4 Surname4"},
"teamleaders":{"0":"Name5 Surname5", "1":"Name6 Surname6"},
}
How can I loop ONLY through employees with JQuery? The below code gives me the whole 3 objects and I can't seem to be able to sort them according to the object name:
$.each(item, function (i, item) {
$.each(item, function (key, value) {
//gives me ALL names and surnames
console.log(value);
})
});
You can use plain JS for this.
for (var employee in json.employees) {
if (json.employees.hasownProperty(employee))
console.log(json.employees[employee])
}
Instead of iterating the outer object, item, do like this.
var item = {
"employees":{"0":"Name1 Surname1", "1":"Name2 Surname2"},
"managers":{"0":"Name3 Surname3", "1":"Name4 Surname4"},
"teamleaders":{"0":"Name5 Surname5", "1":"Name6 Surname6"},
}
$.each(item.employees, function(key, value) { ... });

Null Values in array of objects

I am creating objects when textbox having some values (using ng-blur and textbox.value!==undefined) and then putting these objects in an array (all working fine here).
When I click on checkbox (checkbox model bind with textbox ng-required) I need to delete that particular object having that textbox value.
I am using:
arr.splice(index,1);
to remove that particular object from array (by matching it's name like "monthly" or "quarterly" etc.), but it is creating null at that particular position.
for e.g. [object,object,object]
[
{name:"monthly",
amount:1000 },
{name:"quarterly",
amount:1200 },
{name:"yearly",
amount:1300 }
]
after removing all element it shows [] and when I add another new object it displays [3:object] and it's content as [null,null,null,object];
or
if I remove middle object say name:"quarterly", it shows [object,object] but after adding a new object it display array as [object,object,null,object] with length of array as 4.
Why is there null and how can I remove that from array. (don't want to iterate again to check null).
It is difficult to say why your code creates the null values without have a look to it.
But I can say you that it is not the expected behaviour.
You can see this example to get some inspiration:
var data = [
{name:"monthly",
amount:1000 },
{name:"quarterly",
amount:1200 },
{name:"yearly",
amount:1300 }
];
var newObjectToBeAdded = { name: "daily", amount:"100" }
function showObjects()
{
document.body.innerHTML += data + '<hr>';
}
function deleteObjectByName( objectName )
{
for( var i = 0; i < data.length; i++ )
{
if( data[ i ].name == objectName )
{
data.splice(i, 1);
}
}
}
function addObjectToData( newObject )
{
data.push( newObject );
}
showObjects();
deleteObjectByName( "quarterly" );
showObjects();
addObjectToData( newObjectToBeAdded );
showObjects();
Just to throw a guess out, maybe you are accidentally duplicating the array. Maybe in some point of your code you are doing something like this:
var new_array = original_array.splice( index );
Or creating the new array in the loop you use to find the target object, or using some kind of intermediate array, etc.
Hope it helps!
var arrayWithoutNulls = myArray.filter(function(val) {
if (val) {
return val;
}
});

How to use javascript to loop through key , values and add up one key's value when the other's match

I have a dataset of records that look like this :
[{
"d1d":"2015-05-28T00:00:00.000Z",
"d1h":0,
"d15m":0,
"ct":3
},
{
"d1d":"2015-05-28T00:00:00.000Z",
"d1h":0,
"d15m":0,
"ct":1
}
]
The ct value changes in every record. If d1d, d1h, and d15m are the same in one or more records, I need to combine those records into one with the sum of all the ct values.
I do have jquery, can I use grep for this?
I realize the server side could do a better job of getting me this data , but I have zero control over that.
You don't have to use jQuery for this, vanilla JavaScript will do.
I'll show you two solutions to your problem;
Example 1: Abusing Array#reduce as an iterator
var intermediaryArray = [];
dataset.reduce(function(prev, curr) {
if(prev.d1d === curr.d1d && prev.d1h === curr.d1h && prev.d15m === curr.d15m) {
intermediaryArray.push({
d1d: prev.d1d,
d1h: prev.d1h,
d15m: prev.d15m,
ct: prev.ct + curr.ct
});
} else {
// push the one that wasn't the same
intermediaryArray.push(curr);
}
// return current element so reduce has something to work on
// for the next iteration.
return curr;
});
Example 2: Using Array#Map and Array#Reduce in conjunction
This example utilises underscore.js to demonstrate the logic behind what you want to do.
.map() produces the new array of grouped objects.
.groupBy() produces an array of subarrays containing the objects that pass the predicate that all objects must share the same d1d or grouping function.
.reduce() boils all subarrays down to one value, your object with both cts added to each other.
var merged = _.map(_.groupBy(a, 'd1d'), function(subGroup) {
return subGroup.reduce(function(prev, curr) {
return {
d1d: prev.d1d,
d1h: prev.d1h,
d15m: prev.d15m,
ct: prev.ct + curr.ct
};
});
});
Here's one possible solution:
var dataset = [{
"d1d":"2015-05-28T00:00:00.000Z",
"d1h":0,
"d15m":0,
"ct":3
},
{
"d1d":"2015-05-28T00:00:00.000Z",
"d1h":0,
"d15m":0,
"ct":1
}
]
function addCt(dataset) {
var ctMap = {}
var d1d, d1h, d15m, ct, key, value
for (var ii=0, record; record=dataset[ii]; ii++) {
key = record.d1d+"|"+record.d1h+"|"+record.d15m
value = ctMap[key]
if (!value) {
value = 0
}
value += record.ct
ctMap[key] = value
}
return ctMap
}
ctMap = addCt(dataset)
console.log(ctMap)
// { "2015-05-28T00:00:00.000Z|0|0": 4 }
You may want to construct the key in a different way. You may want set the value to an object containing the d1d, d1h, d15m and cumulated ct values, with a single object for all matching d1d, d1h and d15m values.

Delete an element inside a JSON array by value with jQuery

Part of my json Array
var videos = $j.parseJSON('
[
{ "privacy":"public",
"id":"1169341693" },
{ "privacy":"private",
"id":"803641223" },
{ "privacy":"public",
"id":"1300612600" }, ......
When I console.log the element I'm getting
[Object, Object, Object, …]
0: Object
privacy: "public"
id: "1169341693"
1: Object
privacy: "private"
id: "803641223"
2: Object
privacy: "public"
id: "1300612600"
I also have a unique id I want to search for
var uniqueId = 803641223;
I want to find, in my videos array, the right id, and delete that whole array element. So In that case, I want my final videos array to contain only 2 object, instead of 3 :
var videos = $j.parseJSON('
[
{ "privacy":"public",
"id":"1169341693" },
{ "privacy":"public",
"id":"1300612600" }, ......
My problem is how to get in the array to do my splice. I prefer to do it with jQuery
Any help please?
You can use grep :
videos = $.grep(videos, function(e) { return e.id!='803641223' });
In vanilla JavaScript you could have used the similar filter function but it's not supported by IE8.
Please note that videos is a JavaScript array, it's not a JSON array, even if it was made by parsing a JSON string.
A non-jQuery solution that modifies the array in place:
var uniqueId = 803641223;
var videos = [
{ "privacy":"public",
"id":"1169341693" },
{ "privacy":"private",
"id":"803641223" },
{ "privacy":"public",
"id":"1300612600" }
];
function cleaner(arr, id) {
for (var i = 0; i < videos.length; i++) {
var cur = videos[i];
if (cur.id == uniqueId) {
arr.splice(i, 1);
break;
}
}
}
cleaner(videos, uniqueId);
http://jsfiddle.net/4JAww/1/
Note that this modifies the original array in place, such that the original videos array will have the items you want, and the one that matched the uniqueId will be gone (forever). So it depends on whether you want to be able to access the original array ever again, or are okay with modifying it.
It just loops through the elements of the array, compares the item's id property to the uniqueId value, and splices if they match. I use break; immediately after the splice because you seem to imply that the uniqueId can/should only appear once in the array since it's...unique.
Hello you can remove element with javascript splice function...
videos.items.splice(1, 3); // Removes three items starting with the 2nd,
It worker for me.
arrList = $.grep(arrList, function (e) {
if(e.add_task == addTask && e.worker_id == worker_id) {
return false;
} else {
return true;
}
});
It returns an array without that object.
Hope it helps.

Categories