How to remove item from an array on condition using JavaScript - 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];

Related

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

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)

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;
}
});

making nested objects array and checking if the key exists in objs

I am trying to check if the keys exits in array of objects. I am getting false each time when I pass existing key to my function.
var connect_clients = [];
connect_clients.push({
'a': val
});
function lookup(name) {
for (var i = 0, len = connect_clients.length; i < len; i++) {
if (connect_clients[i].key === name)
return true;
}
return false;
}
console.log(lookup('a'));
Is there anything wrong?
connect_clients[i].key refers to the actual property named key, not the keys of the object.
For this case, you can use Object.keys to get an array of keys of an object and use Array.prototype.some to make sure that at least one of the objects has the key. For example,
function lookup(name) {
return connect_clients.some(function(client) {
return Object.keys(client).indexOf(name) !== -1;
});
}
Use Object.keys() to get keys of an object.
var val = 'val';
var connect_clients = [];
connect_clients.push({
'a': val
});
function lookup(keyName) {
var i;
for ( i = 0; i < connect_clients.length; i++) {
var keys = Object.keys(connect_clients[i]);
if(keys.indexOf(keyName) !== -1) {
return true;
}
}
return false;
}
console.log(lookup('a'));

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();

JavaScript - Compare two multidimensional arrays

I have two multidimensional arrays:
first is something like (['one','one','three'],['four','five',five'],['one','one','one'])
and the second one is like this (['one','one','nine'],['one','one','one'],['two','two'],['two','two','two']...)
Now, what I want is to find match first index of first array with second array, but position of at least first two indexes from boths array must match also, eg.:
first_array (['one','one','three'],['four','five',five'],['one','one','one'])
will match
second_array (['one','one','nine'],['one','one','one'],['two','two']['two','two','two']...)
and output would be eg. 'alert('Match.').
I have tried
for(i=0; i<1; i++){
if(first_array[0] == second_array) console.log('Match');
else console.log('No match');
}
but I constantly get 'No match' although there is a match.
P.S. in 'for' loop, my i is i<1 because I want to compare only first index of first_array with complete second_array.
Thanks in advance
var md1 = [['one','one','three'],['four','five','five'],['one','one','one']];
var md2 = [['one','one','nine'],['one','one','one'],['two','two'],['two','two','two']];
//Iterate through all elements in first array
for(var x = 0; x < md1.length; x++){
//Iterate through all elements in second array
for(var y = 0; y < md2.length; y++){
/*This causes us to compare all elements
in first array to each element in second array
Since md1[x] stays fixed while md2[y] iterates through second array.
We compare the first two indexes of each array in conditional
*/
if(md1[x][0] == md2[y][0] && md1[x][1] == md2[y][1]){
alert("match found");
alert("Array 1 element with index " + x + " matches Array 2 element with index " + y);
}
}
}
Working Example http://jsfiddle.net/2nxBb/1/
Possible duplicate of How to compare arrays in JavaScript?.
For a strict array comparison, check their length and values like so:
var a1 = [1, 2, 3];
var a2 = [1, 2, 3];
array_compare(a1, a2);
function array_compare(a1, a2) {
if(a1.length != a2.length) {
return false;
}
for(var i in a1) {
// Don't forget to check for arrays in our arrays.
if(a1[i] instanceof Array && a2[i] instanceof Array) {
if(!array_compare(a1[i], a2[i])) {
return false;
}
}
else if(a1[i] != a2[i]) {
return false;
}
}
return true;
}
2 way, more simple if this enough for u
JSON.stringify(tree1) === JSON.stringify(tree2)
if not, use this: recursively handles multidimensional arrays and objects
treesAreSame(tree1, tree2) {
if (tree1 === tree2) {
return true;
}
if (tree1 === null || tree1 === undefined || tree2 == null) {
return false;
}
if (Array.isArray(tree1) !== Array.isArray(tree2)) {
return false;
}
if (tree1.length !== tree2.length) {
return false;
}
if (isArray(tree1)) {
for (let i = 0; i < tree1.length; ++i) {
let t1 = tree1[i];
let t2 = tree2[i];
if (isArray(t1) || isObject(t1)) {
if (!treesAreSame(t1, t2)) {
return false;
}
} else {
if (t1 !== t2) {
return false;
}
}
}
}
if (isObject(tree1)) {
for (const k of Object.keys(tree1)) {
let t1 = tree1[k];
let t2 = tree2[k];
if (isArray(t1) || isObject(t1)) {
if (!treesAreSame(t1, t2)) {
return false;
}
} else {
if (t1 !== t2) {
return false;
}
}
}
}
return true;
};
isObject(a) {
return (!!a) && (a.constructor === Object);
};
isArray(a) {
return (!!a) && (a.constructor === Array);
};

Categories

Resources