- Javascript first or default in jquery selector
- Does Javascript have a way of doing «find_if» or «FirstOrDefault»?
- Grouping and get FirstOrDefault LINQ.js
- Where is the flaw in my implementing a firstOrDefault function in Javascript?
- First accordion to be made open by default either by JavaScript or CSS
- How do I FirstOrDefault in Javascript?
- Check the result
- Conclusion
- Javascript ‘First or Default’ function for ‘associative arrays’/objects
- Javascript ‘First or Default’ function for ‘associative arrays’/objects
- FirstOrDefault for javascript
- Does Javascript have a way of doing «find_if» or «FirstOrDefault»?
- Where is the flaw in my implementing a firstOrDefault function in Javascript?
Javascript first or default in jquery selector
Solution 1: Using the browser’s console on the page, I used the following to open the first accordion: Yes, a loop is possible too: Solution 2: Finally, the solution is below: You could write your query like this: Solution: You’re passing the index (0, 1, 2, . ) into , not the value ; you’re also returning the index, not the value, but you said you wanted it to return 9 so that would be the value.
Does Javascript have a way of doing «find_if» or «FirstOrDefault»?
As you already got the mapping, javascript’s Object allows you to directly lookup by key , just check if the object with the key is exist or not.
So you can just use the e.keyCode as key to find if there’s a mapping to it.
var arrowKeyMap = < 37 : "left", 38: "down", 39: "right", 40: "up" >; $(document).keydown(function (e) < var key = arrowKeyMap[e.keyCode]; if (key) < // Do something if there's a map to the key. SG.snake.changeDirection(key ); >>);
You’re thinking too much in terms of algorithms. Think instead in terms of data structures:
You can use JSLinq. It provides the same linq functions for js those are available for c#.
Grouping and get FirstOrDefault LINQ.js
The problem is that you shouldn’t be passing anything into the FirstOrDefault() method. The parameter there is the predicate used to select the first item, it’s not a selector. Just take the first of the group and get the c property.
You could write your query like this:
var query = Enumerable.From(list) .GroupBy("$.a", null, "< a: $, b: $$.Sum('$.b'), c: $$.First().c >") .ToArray();
How to select first radio as default with jquery or javascript, The simplest way to achieve this is to set the checked attribute in the HTML then trigger the change event on that element when the page
Where is the flaw in my implementing a firstOrDefault function in Javascript?
You’re passing the index (0, 1, 2, . ) into f , not the value ; you’re also returning the index, not the value, but you said you wanted it to return 9 so that would be the value.
function firstOrDefault ( arr, f ) < var result = null; var value; // return result; >
Live Example:
function firstOrDefault(arr, f) < var result = null; var value; for (var i = 0, n = arr.length; i < n; ++i) < value = arr[i]; if (f(value)) return value; >return result; >var myArray = [1, 5, 9, 18]; var myFunction = function(x) < return x >5; >; $('#resultdiv').text(firstOrDefault(myArray, myFunction)); // should print 9 inside #resultdiv
Side note: See how I had to add the braces there because I’d added a second statement? FWIW, strongly recommend always using the braces. Your IDE can help.
JQuery :first Selector, The :first selector selects the first element. Note: This selector can only select one single element. Use the :first-child selector to select more than one
First accordion to be made open by default either by JavaScript or CSS
Using the browser’s console on the page, I used the following to open the first accordion:
let allAccordions = document.querySelectorAll(".accordion__item"); allAccordions[0].click();
Yes, a loop is possible too:
Finally, the solution is below:
// Keep the first accordion open by default. let allAccordions = document.querySelectorAll(".accordion__item"); if (allAccordions.length > 0) < allAccordions[0].querySelector("input[type=radio]").checked = true; >// Capture click event for the accordions allAccordions.forEach(element => < element.addEventListener('click', function() < let radioBtn = this.querySelector("input[type=radio]"); let clickedRadioName = radioBtn.getAttribute("name"); allAccordions.forEach(element => < let elementRadioBtn = element.querySelector("input[type=radio]"); let elementRadioName = elementRadioBtn.getAttribute("name"); if ((elementRadioName != clickedRadioName) && elementRadioBtn.checked) < element.querySelector("input[type=radio]").checked = false; >>); >); >);
Jquery get the first element in document order, Maybe aElement.find(«.ui-foo:first») using the jQuery :first selector’? I am not sure if that is more performant though because internally it is
How do I FirstOrDefault in Javascript?
The javascript find function returns either The first item that satisfies the condition or undefined . This means that it behaves like a FirstOrUndefined function.
Consider this list with names:
let names = ["vera", "chuck", "dave"];
Here’s the code where two items match the condition. The first one will be returned:
console.log(names.find(x => x.length === 4));
Here’s the code where none of the items match the condition. undefined will be returned:
console.log(names.find(x => x === "ringo"));
This might be interesting to you, especially if you are used to typing C# code, where the result for nothing-found is null. Checking for null does not work when checking the result for find in Javascript.
Check the result
Here’s the same list and a new variable vera that points to one of the items:
let names = ["vera", "chuck", "dave"]; let vera = names.find(x => x === "vera");
You can check for vera !== undefined like this:
or since undefined is a falsy value, you can omit the !== undefined part
Conclusion
The javascript find function is incredibly powerful and saves you the trouble of looping though items to find an object manually.
I’ve also written about FirstOrDefault in Python and I recommend checking out how it works in that language.
Written by Loek van den Ouweland on 2019-03-12.
Questions regarding this artice? You can send them to the address below.
This website does not need cookies so we don’t use them.
We respect your privacy!
Contact me at
Connect with me on Linked-In
I support open source on Github
My Python tutorials on Youtube
My music on Soundcloud
My online courses on Udemy
Javascript ‘First or Default’ function for ‘associative arrays’/objects
I’m storing values in what some would erroneously call an associated array: The object stores. tokens and a count of documents using that token on a per-db level. I also added a check to prevent cases where the values are retrieved from the prototype chain.
Javascript ‘First or Default’ function for ‘associative arrays’/objects
Is there a better way to do this?
I’m storing values in what some would erroneously call an associated array:
The tokens object stores . tokens and a count of documents using that token on a per-db level.
I can add/remove dbs and tokens and update the docCounts appropriately. We can assume, due to code omitted for brevity, that if a db exists , a token also exists with a docCount of at least 1.
If a db exists and I need to retrieve ANY of its tokens, what is the best method? If the dbs held arrays, it would be as easy as tokens[‘db1’][0] . but I’m not using arrays.
I have something like the following, «inspired» by LINQ (please don’t blame LINQ):
// NOTE: default not implemented here var firstOrDefault = function(obj) < var thing; for (var i in obj) < thing = i; break; >return thing; >;
which would be called as so (simplified for example):
var anyToken; if (tokens['db1')
Generally returning per the above example ‘654321’ (as this is an object, not an array, order is not guaranteed, but either value is acceptable in my code).
- Is this a reasonable method to get any value?
- Is there a better method?
- Should I just **** it up, shove everything into an array, and wrap the storage features that way?
UPDATE: I’ve removed the default reference, as an unfound item will a perfectly acceptable undefined response:
// NOTE: obj.hasOwnProperty not implemented for brevity var firstOrAny = function(obj) < var thing; for (var i in obj) < thing = i; break; >return thing; >;
which would be called as so (simplified for example):
var anyToken; if (tokens['db1')
Slightly shorter solution:
var firstOrDefault = function(obj, d) < for (var i in obj) < if (obj.hasOwnProperty(i)) < return obj[i]; >> return d; >;
But yes, it is the fastest way to get any (usually first inserted) key from an object.
I also added a hasOwnProperty check to prevent cases where the values are retrieved from the prototype chain.
JavaScript Examples, JavaScript Dates. Use Date () to display today’s date and time Use getFullYear () display the year Use getTime () to calculate the number of milliseconds since 1970 Use setFullYear () to set a specific date Use toUTCString () to convert today’s date (according to UTC) to a string Use getDay () to display the weekday as a …
FirstOrDefault for javascript
let array = ["vera", "chuck", "dave"]; let val = array.find(x => x === "vera");
JavaScript Methods, Accessing Object Methods. You access an object method with the following syntax: objectName.methodName () You will typically describe fullName () as a method of the person object, and fullName as a property. The fullName property will execute (as a function) when it is invoked with (). This example accesses the fullName () …
Does Javascript have a way of doing «find_if» or «FirstOrDefault»?
I’m a Junior- level JavaScript developer and I find that I often have situations where I need to do the equivalent of
"Find the first element satisfying a condition, then do something with the element"
and I end up writing a for loop with a break statement. For instance, here is a piece of production code I wrote:
// set up event listeners for changing the snake's direction // based on arrows keys pressed // see: http://stackoverflow.com/questions/6226859/how-can-i-track-arrow-keys-in-chrome-and-ie var arrowKeyMap = < 37 : "left", 38: "down", 39: "right", 40: "up" >; $(document).keydown(function (e) < // want to make this more compact . for (var i in arrowKeyMap) < if (i == e.keyCode) < SG.snake.changeDirection(arrowKeyMap[i]); break; >> >);
I want to know if there is a native JavaScript tool, or a way using JQuery, make that more compact, or if I need to hand-roll a reusable procedure for situations like this. I know that C# has a FirstOrDefault and C++ a find_if which are kinda like what I want.
As you already got the mapping, javascript’s Object allows you to directly lookup by key , just check if the object with the key is exist or not.
So you can just use the e.keyCode as key to find if there’s a mapping to it.
var arrowKeyMap = < 37 : "left", 38: "down", 39: "right", 40: "up" >; $(document).keydown(function (e) < var key = arrowKeyMap[e.keyCode]; if (key) < // Do something if there's a map to the key. SG.snake.changeDirection(key ); >>);
You’re thinking too much in terms of algorithms. Think instead in terms of data structures:
You can use jslinq . It provides the same linq functions for js those are available for c#.
FirstOrDefault for javascript Code Example, Javascript queries related to “firstOrDefault for javascript” firstordefault() firstordefault in javascript; firstordefault example; array firstordefault javascript; first or default object javascript; firstordefault in jjs; node js firstordefault; js array firstordefault; firstordefault().value; …
Where is the flaw in my implementing a firstOrDefault function in Javascript?
I’m trying to practice my Javascript chops and am trying to figure out the flaw in my attempted implementation of a firstOrDefault function like exists in C#.
function firstOrDefault ( arr, f ) < var result = null; for ( var i = 0, n = arr.length; i < n; ++i ) if (f(i)) return i; return result; >$(document).ready(function() < var myArray = [1, 5, 9, 18]; var myFunction = function ( x ) < return x >5; >; $('#resultdiv').text(firstOrDefault(myArray, myFunction)); // should print 9 inside #resultdiv >);
Fiddle: http://jsfiddle.net/z3h06mwo/
Also, should I instead be extending Array ? If so, how do I do that?
You’re passing the index (0, 1, 2, . ) into f , not the value ; you’re also returning the index, not the value, but you said you wanted it to return 9 so that would be the value.
function firstOrDefault ( arr, f ) < var result = null; var value; // return result; >
Live Example:
function firstOrDefault(arr, f) < var result = null; var value; for (var i = 0, n = arr.length; i < n; ++i) < value = arr[i]; if (f(value)) return value; >return result; >var myArray = [1, 5, 9, 18]; var myFunction = function(x) < return x >5; >; $('#resultdiv').text(firstOrDefault(myArray, myFunction)); // should print 9 inside #resultdiv
Side note: See how I had to add the braces there because I’d added a second statement? FWIW, strongly recommend always using the braces. Your IDE can help.
FirstOrDefault() in js Code Example, firstordefault example. array firstordefault javascript. first or default object javascript. firstordefault for javascript. first () and when to use firstordefault () firstordefault in jquery. node js firstordefault. get first or default of firstordefault. javascript list first or default.