Get Item from Array with Property equal to Value - javascript

This questions is for my LightSwitch project but I'm not sure that's renavent. I've never done javascript or jquery before and i'm pretty sure this will have nothing to do with LightSwitch and everything to do with the latter.
The following code works perfectly setting test equal to 4 in my case:
myapp.BrowseTreeNodes.TreeNodes_render = function (element, contentItem) {
var screen = contentItem.screen;
var result = screen.MyArray.data[0];
var test = result.Id;
}
What I need to do is instead of setting result to the first item in the array I need to set result to the item with a specific Id, for this example let's say 4.
Here's what i've tried:
var result = $.grep(screen.MyArray.data, function (e) { return e.Id === 4; })[0];
var result = screen.MyArray.data.filter(function (v) { return v.Id === 4; })[0];
var result = screen.MyArray.data.find(x => x.Id === 4)[0];
Thank you in advance.

your problem may be the === , === checks for type as well, so "4" === 4 is false while "4" == 4 is true, check if your id property is stored as a string or an integer...

Related

How to check if less than 2 of 3 variables are empty

I need to check that there are at least 2 values before running a script, but can't seem to get the condition to fire.
When I use if (risForm) {... the script runs when risForm is filled, and when I use if (!(risForm)) {... the script runs if risForm is empty, but I can't seem to work out how to check if any 2 of the three is full... I've tried this:
if ((!(risForm)) + (!(runForm)) + (!(angForm)) < 2) {...
along with a numerous adjustments to precise formatting/bracketting, but it's not getting me anywhere!
Make an array of the variables, filter by Boolean, then check the length of the array:
const forms = [risForm, runForm, angForm];
if (forms.filter(Boolean).length < 2) {
throw new Error('Not enough forms are filled');
}
// rest of the code
You can avoid creating an intermediate array by using reduce instead, if you wanted:
const filledFormCount = forms.reduce((a, form) => a + Boolean(form), 0);
if (filledFormCount < 2) {
throw new Error('Not enough forms are filled');
}
If you can have all your variables inside an array, you can do
yourArray.filter(Boolean).length >= 2
To break it apart, let's rewrite the above in a more verbose fashion:
yourArray
.filter(
function (variable) {
return Boolean(variable)
}
)
.length >= 2
Now, array.filter() gets every variable in the array and runs each as the argument for the function inside the parens, in this case: Boolean(). If the return value is truthy, the variable is "filtered in", if not it is "filtered out". It then returns a new array without the variables that were filtered out.
Boolean() is a function that will coerce your value into either true or false. If there's a value in the variable, it will return true... But there's a catch: it will return false for zeroes and empty strings - beware of that.
Finally, we use .length to count how many variables were "filtered in" and, if it's more than two, you can proceed with the code.
Maybe this pseudo code can illustrate it better:
const variables = ['foo', undefined, 'bar'];
variables.filter(Boolean).length >= 2;
['foo', undefined, 'bar'].filter(Boolean).length >= 2;
keepIfTruthy(['foo' is truthy, undefined is falsy, 'bar' is truthy]).length >= 2;
['foo', 'bar'].length >= 2;
2 >= 2;
true;
Javascript's true and false are useful here because when coerced to a number, they become respectively 1 and 0. So...
function foo(a,b,c) {
const has2of3 = !!a + !!b + !!c;
if ( has2of3 ) {
// Do something useful here
}
}
One caveat, though is that the empty string '' and 0 are falsy, which means they would be treated as not present. If that is an issue, you could do something like this:
function foo(a,b,c) {
const hasValue = x => x !== undefined && x !== null;
const has2of3 = hasValue(a) + hasValue(b) + hasValue(c);
if ( has2of3 ) {
// Do something useful here
}
}
let risForm = "a",
runForm = "",
angForm = "";
let arr = [risForm, runForm, angForm]
let res = arr.filter(el => !el || el.trim() === "").length <= 1
console.log(res)
There many ways to solve this. Lets try with basic idea. You want to make a reusable code and something that support multiple variables, also condition value might change. This means, we need to define an array of the form values and a condition value to verify. Then we can apply a function to verify the condition. So let's try some code:
let risForm, runForm, angForm;
risForm = 'Active';
// runForm = 3;
const formValues = [risForm, runForm, angForm];
const minFilledForms = 2;
const hasValue = a => !!a && a !== undefined && a !== null;
verifyForms();
function verifyForms() {
let filledForms = formValues.reduce((count, form) => count + hasValue(form), 0);
if (filledForms < minFilledForms) {
console.log(`Only ${filledForms} of ${formValues.length} forms have filled. Minimum ${minFilledForms} forms are requiered.`);
}
console.log('Continue...');
}

Set property on object while iterating

I am making a SPA with Laravel(backend) and Vue.js. I have the following arrays:
accessArray:
["BIU","CEO","Finance","HRD","Group"]
access:
["BIU","Group"]
I want to compare the access array to the accessArray array and if there is a match to change the record (in the accessArray) and add a true value otherwise add a false value. I am doing this inside a Vue method.
... so far I got this:
var foo = ["BIU","CEO","Finance","HRD","Group"];
var bar = ["BIU","Group"];
$.each(bar, function (key, value) {
if ($.inArray(value, foo) != -1) {
var position = $.inArray(value, foo);
console.log(value + ' is in the array. In position ' + position);
foo[position] = {name: value, checked: true};
}
});
Which outputs this to the console:
BIU is in the array. In position 0
Group is in the array. In position 4
And this in Vue:
[
{"name":"BIU","checked":true},
"CEO",
"Finance",
"HRD",
{"name":"Group","checked":true}
]
The output I would like to achieve is the following:
[
{"name":"BIU","checked":true},
{"name":"CEO","checked":false},
{"name":"Finance","checked":false},
{"name":"HRD","checked":false},
{"name":"Group","checked":true}
]
Any help would be greatly appreciated, I have looked at many similar problems on SO but cant seem to find anything along these lines. I have also tried to add an else statement on the end but I (think) I'm converting it to an object so that doesn't seem to work.
Edit:
The data in foo comes from a Laravel config setting so is somewhat dynamic
The data in bar is JSON received from the Laravel ORM (its json stored in a text field)
An option with vanilla javascript:
var foo = ["BIU","CEO","Finance","HRD","Group"];
var bar = ["BIU","Group"];
var result = foo.map(name => {
var checked = bar.indexOf(name) !== -1
return { name, checked }
})
console.log(result)
You can use Array#map to iterate over the array and construct a new one, by checking if values are present in the other one through Array#includes
const accessArray = ["BIU","CEO","Finance","HRD","Group"];
const access = [ "BIU", "Group" ];
const result = accessArray.map( a => ({ name: a, checked: access.includes(a)}) ) ;
console.log(result);
A note: when using an arrow function and you want to return an object, you need to surround the object literal in () otherwise it would be interpreted as a code block.
Use reduce and inside the reduce call back check if the item is present in both accessArray & access . Create an object and the item present in both array set the value of checked to true or false
let arr1 = ["BIU", "CEO", "Finance", "HRD", "Group"]
let arr2 = ["BIU", "Group"];
let k = arr1.reduce(function(acc, curr) {
let obj = {}
if (arr2.includes(curr)) {
obj.name = curr;
obj.checked = true
} else {
obj.name = curr;
obj.checked = false
}
acc.push(obj);
return acc;
}, []);
console.log(k)
To achieve expected result use below option
1. Loop foo array
2.Remove initial if condition - "if ($.inArray(value, foo) != -1)" to loop through all
3. Do conditional check for checked - checked: $.inArray(value, bar) !== -1 ? true : false
codepen - https://codepen.io/nagasai/pen/GXbQOw?editors=1011
var foo = ["BIU","CEO","Finance","HRD","Group"];
var bar = ["BIU","Group"];
$.each(foo, function (key, value) {
foo[key] = {name: value, checked: $.inArray(value, bar) !== -1 ? true : false};
});
console.log(foo);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Option 2:
Without using jquery and using simple forEach to loop through foo
codepen - https://codepen.io/nagasai/pen/YOoaNb
var foo = ["BIU","CEO","Finance","HRD","Group"];
var bar = ["BIU","Group"];
foo.forEach((v,i) => foo[i] = {name: v , checked : bar.includes(v)})
console.log(foo);

How to check if a certain object is the only object in a JavaScript array?

if (myArray contains only myObject) {
//Do stuff...
} else {
//Do different stuff...
}
What should I do to make the if (myArray contains only myObject) line actually check if myArray contains only myObject?
The object will not be in the array more than once and will be in position 1 (not position 0) only. So, using myArray.length won't help (maybe?).
I'm using .splice to add an object into myArray at position 1 so position 0 should be undefined.
Based on your question i can only deduce the following are what you want
A particular object shouldn't be in the array more than once.
The Length of the array shouldn't be greater than 2, which will
answer that you maybe only want an object in the array but the first
element can be undefined tho.
A proper way to do this will be:
let myArray = [undefined, "object", "object"];
//check that myArray only contains "object"
//1: The "object" should not be in the array more than once
//2: I presume you also want the array length not to be greater than 2
console.log(containsObjectOnly("object", myArray));
function containsObjectOnly(obj, myArray) {
var isOnly = false;
let xTimes = 0;
let found = myArray.filter((value) => {
if (value == obj && xTimes === 0) {
isOnly = true;
xTimes++;
} else if (xTimes > 0 && value == obj) {
isOnly = false;
}
return isOnly;
});
return isOnly && !(myArray.length > 2);
}
you want to check two conditions:
first, the length of the array can only be 2 (since we have the object at instance 1)
second, the first index must be undefined.
so
if(myArray.length ==2 && myArray[0] === undefined &&(myArray[1] == myObject)){
//some code
}else{
//some other code
}
edit: just a note, we can still take advantage of the array length since we know that the index we set is [1]
ie. [undefined,{our object}];
if (myArray.length === 1 && JSON.stringify(myObject) === JSON.stringify(myArray[0])) {
console.log("myObject is in here, and it's the only element!");
}
else {
console.log('nope!');
}

linq.js return value of (default) FirstOrDefault

Trying to check on the result of linq.js FirstOrDefault(), but checking for null or undefined isn't working. Having some trouble debugging it, but I can see that it is returning some sort of object.
There isn't any documentation for this method online that I could find.
I've tried:
var value = Enumerable.From(stuff).FirstOrDefault('x => x.Name == "Doesnt exist"')
if (value) {
alert("Should be not found, but still fires");
}
if (value != null)
alert("Should be not found, but still fires");
}
The signatures for the FirstOrDefault() function is:
// Overload:function(defaultValue)
// Overload:function(defaultValue,predicate)
The first parameter is always the default value to return if the collection is empty. The second parameter is the predicate to search for. Your use of the method is wrong, your query should be written as:
var value = Enumerable.From(stuff)
.FirstOrDefault(null, "$.Name === 'Doesnt exist'");
We figured out the answer as I was typing this out. Since there is so little documentation, I'll share.
You need to move the lambda into a Where clause before the FirstOrDefault().
When
var someArray = ["Foo", "Bar"];
var result = Enumerable.From(someArray).Where('x => x == "Doesnt exist"').FirstOrDefault();
Result is undefined (correct)
When
var someArray = ["Foo", "Bar"];
var result = Enumerable.From(someArray).Where('x => x == "Bar"').FirstOrDefault();
Result is 'Bar' (correct)
When
var someArray = ["Foo", "Bar"];
var result = Enumerable.From(someArray).FirstOrDefault('x => x == "Bar"');
Result is 'Foo' (incorrect)

How can I check JavaScript arrays for empty strings?

I need to check if array contains at least one empty elements. If any of the one element is empty then it will return false.
Example:
var my_arr = new Array();
my_arr[0] = "";
my_arr[1] = " hi ";
my_arr[2] = "";
The 0th and 2nd array elements are "empty".
You can check by looping through the array with a simple for, like this:
function NoneEmpty(arr) {
for(var i=0; i<arr.length; i++) {
if(arr[i] === "") return false;
}
return true;
}
You can give it a try here, the reason we're not using .indexOf() here is lack of support in IE, otherwise it'd be even simpler like this:
function NoneEmpty(arr) {
return arr.indexOf("") === -1;
}
But alas, IE doesn't support this function on arrays, at least not yet.
You have to check in through loop.
function checkArray(my_arr){
for(var i=0;i<my_arr.length;i++){
if(my_arr[i] === "")
return false;
}
return true;
}
You can try jQuery.inArray() function:
return jQuery.inArray("", my_arr)
Using a "higher order function" like filter instead of looping can sometimes make for faster, safer, and more readable code. Here, you could filter the array to remove items that are not the empty string, then check the length of the resultant array.
Basic JavaScript
var my_arr = ["", "hi", ""]
// only keep items that are the empty string
new_arr = my_arr.filter(function(item) {
return item === ""
})
// if filtered array is not empty, there are empty strings
console.log(new_arr);
console.log(new_arr.length === 0);
Modern Javascript: One-liner
var my_arr = ["", "hi", ""]
var result = my_arr.filter(item => item === "").length === 0
console.log(result);
A note about performance
Looping is likely faster in this case, since you can stop looping as soon as you find an empty string. I might still choose to use filter for code succinctness and readability, but either strategy is defensible.
If you needed to loop over all the elements in the array, however-- perhaps to check if every item is the empty string-- filter would likely be much faster than a for loop!
Nowadays we can use Array.includes
my_arr.includes("")
Returns a Boolean
You could do a simple help method for this:
function hasEmptyValues(ary) {
var l = ary.length,
i = 0;
for (i = 0; i < l; i += 1) {
if (!ary[i]) {
return false;
}
}
return true;
}
//check for empty
var isEmpty = hasEmptyValues(myArray);
EDIT: This checks for false, undefined, NaN, null, "" and 0.
EDIT2: Misread the true/false expectation.
..fredrik
function containsEmpty(a) {
return [].concat(a).sort().reverse().pop() === "";
}
alert(containsEmpty(['1','','qwerty','100'])); // true
alert(containsEmpty(['1','2','qwerty','100'])); // false
my_arr.includes("")
This returned undefined instead of a boolean value so here's an alternative.
function checkEmptyString(item){
if (item.trim().length > 0) return false;
else return true;
};
function checkIfArrayContainsEmptyString(array) {
const containsEmptyString = array.some(checkEmptyString);
return containsEmptyString;
};
console.log(checkIfArrayContainsEmptyString(["","hey","","this","is","my","solution"]))
// *returns true*
console.log(checkIfArrayContainsEmptyString(["yay","it","works"]))
// *returns false*
yourArray.join('').length > 0
Join your array without any space in between and check for its length. If the length, turns out to be greater than zero that means array was not empty. If length is less than or equal to zero, then array was empty.
I see in your comments beneath the question that the code example you give is PHP, so I was wondering if you were actually going for the PHP one? In PHP it would be:
function hasEmpty($array)
{
foreach($array as $bit)
{
if(empty($bit)) return true;
}
return false;
}
Otherwise if you actually did need JavaScript, I refer to Nick Craver's answer
Just do a len(my_arr[i]) == 0; inside a loop to check if string is empty or not.
var containsEmpty = !my_arr.some(function(e){return (!e || 0 === e.length);});
This checks for 0, false, undefined, "" and NaN.
It's also a one liner and works for IE 9 and greater.
One line solution to check if string have empty element
let emptyStrings = strArray.filter(str => str.trim().length <= 0);
let strArray = ['str1', '', 'str2', ' ', 'str3', ' ']
let emptyStrings = strArray.filter(str => str.trim().length <= 0);
console.log(emptyStrings)
One line solution to get non-empty strings from an array
let nonEmptyStrings = strArray.filter(str => str.trim().length > 0);
let strArray = ['str1', '', 'str2', ' ', 'str3', ' ']
let nonEmptyStrings = strArray.filter(str => str.trim().length > 0);
console.log(nonEmptyStrings)
If you only care about empty strings then this will do it:
const arr = ["hi","hello","","jj"]
('' in arr) //returns false
the last line checks if an empty string was found in the array.
I don't know if this is the most performant way, but here's a one liner in ES2015+:
// true if not empty strings
// false if there are empty strings
my_arr.filter(x => x).length === my_arr.length
The .filter(x => x) will return all the elements of the array that are not empty nor undefined. You then compare the length of the original array. If they are different, that means that the array contains empty strings.
You have to check in through the array of some functions.
if isEmptyValue is true that means the array has an empty string otherwise not.
const arr=['A','B','','D'];
const isEmptyValue = arr.some(item => item.trim() === '');
console.log(isEmptyValue)
array.includes("") works just fine.
Let a = ["content1", "" , "content2"];
console.log(a.includes(""));
//Output in console
true

Categories

Resources