angularjs: check for an id exists in an array r not - javascript

var vm = this;
vm.usableDeposits = [];
for (var i = 0; i < billableChargeCodes.length; i++) {
var deposits = usableDeposits.filter(function(ud) {
return ud.billinggroupuid == billableChargeCodes[i].billinggroupuid ||
ud.billinggroupuid == billableChargeCodes[i].billingsubgroupuid ||
ud.departmentuid == billableChargeCodes[i].departmentuid ||
!ud.entypeuid ||
ud.entypeuid == entypeuid
})
for (var i = 0; i < deposits.length; i++) {
var depositid = deposits[i]._id;
first time, vm.usableDeposits[] is empty. I have to check deposits[i]._id exists in vm.usableDeposits[] or not. How to check vm.usableDeposits[] empty array _id with deposits[i]._id? if id not exists in vm.usableDeposits[], then i want to push the element into vm.usableDeposits[]

You can simply use the indexOf operator in JavaScript to check if a value exists in the array or not. It returns -1 if the value is not in the array, else, it returns the index of the element in the array.
The syntax goes like this -
if(myArray.indexOf(value) !== -1) {
// do this
} else {
// do that
}
Hope this helps.

You can use .some
deposits.some(o=> vm.usableDeposits.indexOf(o.id))
to check if the ID in deposits array is in vm.usableDeposits. .some will return true if condition is true and false otherwise

$scope.findIndexInData = function(data, property, value) {
var result = -1;
if((!!data) && (!!property) && (!!value)){
data.some(function (item, i) {
if (item[property] === value) {
result = i;
return true;
}
});
}
return result;
}
Pass on the array as the First Element. Property as second element and value you are looking in that array.
Example:
array = [{id:"1234",name:"abc"}, {id:"4567",name"xyz"}]
So you need to call:
index = $scope.findIndexInData(array , 'id' , 4567)

Related

How to remove item from an array on condition using JavaScript

I have an an array which is mentioned below. I would like to remove an item from the array which has empty property value using JavaScript.
Actual array:
[
{
"href":"/client",
"methods":[]
},
{
"href":"/home",
"methods":
{
"type1":"GET",
"type2":"POST",
}
},
{
"href":"/about",
"methods":[]
},
{
"href":"/contact",
"methods":
{
"type1":"GET",
"type2":"POST",
}
}
]
Expecting result:
[
{
"href":"/home",
"methods":
{
"type1":"GET",
"type2":"POST",
}
},
{
"href":"/contact",
"methods":
{
"type1":"GET",
"type2":"POST",
}
}
]
This is the job for filter. however filter does not modify the existing array so you need to assign it to a different array/overwrite the current variable
a = a.filter(item => Object.keys(item.methods).length > 0)
Iterate over the object array and filter based on methods property length.
var obj = [...];
obj = obj.filter((val) => val.methods && val.methods.length !== 0);
In the case of methods, you can easily walk the object and then call delete on the keys with values that are empty.... or empty arrays. I expanded the answer to cover not only keys of methods where an array is empty, but all keys with what i would define as empty contents.
var l = [];
for (var i = 0; i < l.length; i++){
var keys = Object.keys(l[i]);
for ( var j = 0; j < keys.length; j++){
var value = keys[j];
// In your use case, you are only doing arrays so i coded it as such.
if (value.length == 0){
delete l[i][j];
}
}
}
If you want to expand it to cover a variety of cases such as empty string, empty arrays, empty maps, or null values you can defined a function to do that.
function isValueDeletable(value){
if (value == null) return true;
if (value == "") return true;
if (value instanceof Array && value.length == 0) return true;
if (value instanceof Map && Object.keys(value).length == 0) return true;
return false;
}
and apply that instead of the value.length == 0;
if (isValueDeletable(value)){ delete l[i][j]; }
Then l is modified to remove all keys with empty values.
enter var json = {};
var key = "giveitakeyvalue";
json[key] = null;
delete json[key];

Javascript Searching Array for partial string

Have a function that returns an array of objects. The array has a rate object that has a name field. Inside the name field are names such as "Slow speed" and "Fast speed".
I have written the following in hopes to create a new array that will filter out the array values and just return only those with "Slow" that matches from the rates[i].name.
So far I am encountering this error in my dev console.
"Uncaught TypeError: value.substring is not a function"
var rates = myArray();
var index, value, result;
var newArr = [];
for (index = 0; index < rates.length; ++index) {
//value = rates[index];
if (value.substring(0, 5) === "Stand") {
result = value;
newArr.push();
break;
}
}
Part of array return in console.
"rates":[{"id":1123,"price":"1.99","name":"Slow speed - Red Car","policy":{"durqty":1,"durtype":"D","spdup":15000,"spddwn":15000}
You have an object at each array location not the string itself, try this instead:
var rates = myArray();
var index, value, result;
var newArr = [];
for (index = 0; index < rates.length; ++index) {
name = rates[index].name;
if (name.substring(0, 4) === "Slow") {
newArr.push(rates[index]);
}
}
Try using filter function like this, it is much more cleaner to see
var newArr = rates.filter(function(rate){
return rate.name && rate.name.substring(0,4) === "Slow";
});
You can use filter to do this, for example:
var newArr = rates.filter(function(val){
// check if this object has a property `name` and this property's value starts with `Slow`.
return val.name && val.name.indexOf("Slow") == 0;
});
As #4castle mentioned, instead of indexOf(...) you can use slice(...) which may be more efficent, eg: val.name.slice(0,4) == "Slow"

Removing outer array object if an inner array meets a condition

I am dealing with a fairly complex object. It contains 2 arrays, which contain 3 arrays each of objects:
I'm trying to delete one of the history: Array[2] if one of the objects in it has username: null.
var resultsArray = result.history;
var arrayCounter = 0;
resultsArray.forEach(function(item) {
item.forEach(function(innerItem) {
if (innerItem.username == null) {
resultsArray.splice(arrayCounter,1);
};
});
arrayCounter++;
});
Looking through answers it's recommended to do something like:
resultsArray.splice(arrayCounter,1);
This isn't working in this situation because more than one of the objects could have username == null and in that case it will delete multiple history objects, not just the one that I want.
How do I remove only the one specific history array index if username == null?
splice is evil. I think using immutable array methods like filter might be easier to reason about:
x.history =
x.history.filter(function (h) {
return !h.some(function (item) {
return item.username === null
})
})
Go through all the histories, and do not include them in the filter if they have a username that is null.
My understanding was that you only want to delete the first outer array that has an inner array that has an object with a null username. Heres one solution closest to your current form:
var resultsArray = result.history;
var arrayCounter = 0;
var foundFirstMatch = false;
resultsArray.forEach(function(item) {
if (!foundFirstMatch) {
item.forEach(function(innerItem) {
if (innerItem.username == null && !foundFirstMatch) {
foundFirstMatch = true;
};
});
arrayCounter++;
}
});
if (foundFirstMatch > 0)
resultsArray.splice(arrayCounter, 1);
Other syntax:
var resultsArray = result.history;
var outerNdx;
var innerNdx;
var foundMatch = false;
for (outerNdx = 0; !foundMatch && outerNdx < resultsArray.length; outerNdx++) {
for (innerNdx = 0; !foundMatch && innerNdx < resultsArray[outerNdx].length; innerNdx++) {
if (resultsArray[outerNdx][innerNdx].username == null) {
foundMatch = true;
}
}
}
if (foundMatch)
resultsArray.splice(outerNdx, 1);
Update - here's how I'd do it now, without lodash:
thing.history.forEach((arr, i) => {
thing.history[i] = arr.filter( (x) => x.username !== null );
});
Previous answer:
I'd use lodash like this:
_.each(thing.history, function(array, k){
thing.history[k] = _.filter(array, function(v){
return v.username !== null;
})
});
Here's a jsfiddle:
https://jsfiddle.net/mckinleymedia/n4sjjkwn/2/
You should write something like this:
var resultsArray = result.history.filter(function(item){
return !item.some(function(inner){ return inner.username==null; });
});
The foreach loop cant break in this way but a regular for loop can. This is working:
result.history.forEach(function(item) {
loop2:
for (var i = 0; i < item.length; i++) {
var innerItem = item[i];
console.log(innerItem);
break loop2;
}
});

angularjs remove array specific element dosen't work

if I push two elements into another array and then try to remove the first one ( click at the first button ) the second element is being removed. why ?!?
DEMO
$scope.removeFromList = function(p) {
$scope.found = $.grep($scope.data2, function(e) {
return e.ID == p.ID;
});
var index = $scope.data2.indexOf($scope.found);
$scope.data2.splice(index, 1);
}
indexOf works for array not for Object. It returns -1, and so always take the last element.
Try this:
$scope.removeFromList = function (p) {
var index = $scope.data2.map(function(e) { return e.ID;}).indexOf(p.ID);
if(index >= 0)
$scope.data2.splice(index, 1);
}
This is happend because indexof is not used to find the objects and return -1 index always which in turn remove the first element always you need to create your own indexof
var index = myIndexOf($scope.data2,$scope.found);
function myIndexOf(arr,o) {
for (var i = 0; i < arr.length; i++) {
if (arr[i].x == o.x && arr[i].y == o.y) {
return i;
}
}
return -1;
}
Plunker

How to check if all fields whose names are given in an array are non-null?

I have a javascript array which contains the name of fields in a record:
fields=["size", "Hold","drawn%" ,"expiry"]
I need to persorm an operation,if the value in ALL these fields is not null.
I can iterate the array and check a not-null condition on each element.
Is there a better way to handle this; wherein each member of the array has to be evaluated against a particular condition, and return a cumulative true or false.
fields.every(function(name, i) { return record[name] !== null; })
will return true if every field from fields in record is not null, and false otherwise.
Array.prototype.IsNull = function() {
var arr = this;
var isNull = false;
for (var i = 0; i < arr.length; i++) {
if (arr[i] == null) {
isNull = true;
break;
}
}
return isNull;
};
var fields=["size", "Hold","drawn%" ,"expiry"];
var isNull = fields.IsNull();

Categories

Resources