Better jQuery object filtering [closed] - javascript

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Working on a js app involving many objects, I want to be able to grab an object by a specific variable. Here is my code:
var pin = '0000';
$.each(employees, function(){
if(this.pin === pin){
curEmployee = this;
return false;
}
});
Though this approach works, I have a feeling that there are way better solutions out there... I was fiddling around with grep and tried:
var pin = '0000';
curEmployee = $.grep(employees, function(e,i){
return e[pin] === pin;
});
However, it is harder to determine a result, since now I will need to check the length to see if an array with provided back, and such.
Just looking for a best practices solution.

Since an Array is always returned from $.grep, just get the [0] index of the Array. If undefined, there was no match.
var pin = '0000';
curEmployee = $.grep(employees, function(e,i){
return e.pin === pin;
})[0]; // <--- always grab the first index
Without jQuery, you could use Array.prototype.filter in the same manner:
var pin = '0000';
curEmployee = employees.filter(function(e,i){
return e.pin === pin;
})[0];

You could always use jquery's filter method:
var pin = '0000';
curEmployee = $(employees).filter(function(e){
return e.pin === pin;
})[0];

In All honesty, IF you are using aloot of objects and performance is important...
.. and you want to avoid the asynchronous bugies in js.. you should go for a pure js. approach.
Something like for loop which god trough all objects. And possibly some result buffering. I know it is a pain in the ass and you probably wont like to do it. but it is the fastest way in most cases.
I personally use such aproach in a js. crm we are making, becouse the jquery way was a no go on 1000+ objects...

Related

How to Get Unique Elements from a DOM Collection in Vanilla JavaScript ES6+ [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I have a JavaScript function that returns an array of Node or Element, but it contains duplicates. I searched around and found functions to get the unique items of an array, but it seems to work only on strings or simple types, when applying it to the DOM array, it does nothing. I assume it has to do with the items being objects.
Using ES6's Set as some answers suggest doesn't work. Another suggestion uses a filter function to check if the item already has an index in the array. Again, neither works for the DOM objects.
I'd appreciate it if someone could point to how I can remove the duplicates. Thanks in advance!
Update
#Kroltan seems to have understood what I mean, but for everyone else, here's a function that returns duplicate nodes:
function (
selector) {
const children = Array.from(this.parent().children).filter((
v) => v !== this);
if (!selector) {
return children;
}
return children.filter((
v) => v.matches && v.matches(selector));
}
If I were to do something like $("div"), I will get a lot of duplicates depending on nesting. I want to shrink the returned array of nodes to have no duplicates similar to how jQuery's implementation does it. Here's an example screenshot of my version (1) and jQuery's version (2). I want to get them to match.
Update 2
Figured it out. The Set solution works, but I was applying it to the wrong array and so I wasn't seeing the result I was expecting. Now that I'm applying it to the right array, it works, imagine that... :)
Those solutions do work. But they work on the principle of referential equality.
You're probably looking to remove structural duplicates, (e.g. a bunch of <br> elements or whatnot) that's trickier, and you'll have to decide on a criterion for their equality yourself. Something like Lodash's uniqBy. (check its source to see how it works!)

What is the most efficient way to find an element in an array? [duplicate]

This question already has answers here:
Find object by id in an array of JavaScript objects
(36 answers)
Closed 7 years ago.
I get an array of objects from the backend as this one, currently only three elements but in the future will be more.
[{"code":"lng.dropdown.home","text":"Inicio"},
{"code":"lng.dropdown.shop","text":"Tienda"},
{"code":"lng.button.support","text":"Soporte"}]
What is the most efficient way in javascript to find an element in this array by code, and return the text associated? Can we use lambdas expresions here?
you can use array filter to find the nested object(s) that matches your code property:
var arr =
[{"code":"lng.dropdown.home","text":"Inicio"},
{"code":"lng.dropdown.shop","text":"Tienda"},
{"code":"lng.button.support","text":"Soporte"}];
var res = arr.filter(function(x){
return x.code == 'lng.dropdown.home'
})
console.log(res[0])
[].filter returns an array with the objects that return true inside the callback.
As far as efficiency is concerned for loop are proved to be faster but using higher order methods you earn abstraction .
When not using other libraries, I usually map then find the indexOf, as follows:
data[data.map(function(a){ return a.code }).indexOf("code I am trying to find")];
This returns the element of data at the index where code matches the code you're trying to find.
When I have lodash as a dependency, I usually just do this however:
_.find(data, {code:"code I am trying to find"})
(I think that's the proper syntax)
Edit:
Didn't realize you were already using JQuery, the answer using $.grep is probably best.

about conditionals in javascript [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I have some (I think they can be few stupid) questions...but they're questions, and I'd like post here, and debate it.
It's about conditionals. I'm developing in javascript, and I've some functions, and I'd like write optimal code.
For example, I have to check some conditions, so I can write:
if(text == ""){
//some code for finish
}else if(text== previousText){
//some code for finish
}
//here I write more code...which runs if both conditions had not complied.
My doubt is: what do you think is better to do?
Point 1
if(text == ""){
//some code for finish
}else if(text== previousText){
//some code for finish
}else{
//here I write more code...which runs if both conditions had not complied.
}
or
Point 2
if(text == ""){
//some code for finish using return
return;
}else if(text== previousText){
//some code for finish using return
return;
}
//here I write more code...which runs if both conditions had not complied.
I hope have explained well. Sometimes these things go unnoticed, but they're important, I think.
Thanks a lot, Daniel
I follow the rule to have only one return statement per function. So Point 1

How do I go from codecademy to actual programming? Specific example included [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
So I have been spending a lot of time lately on codecademy and it is amazing. I feel like I am starting to really grasp JavaScript and programming in general. However, I want to start the basics of implementing my new skills into use. I am sure I am not alone with this desire and while I have some books coming in the mail (for jQuery, Ajax and Ruby) I thought Stack Overflow might be a good place to start.
Let's say for example I wanted to use the code (or something like it) below that I just wrote to calculate someones BMI and interpret it for them. It prompts them to input their weight and height and then calculates their BMI.
The code works in the codecademy scratch pad but I would have no idea how to put this code to use in the real world. I have a feeling it would have something to do with creating an HTML form and taking the input names as variables but I'm not sure.
If this isn't the correct place to ask the question, I apologize, this is my first question on Stack Overflow!
var weight = prompt("How much do you weigh, in pounds?");
var height = prompt("How tall are you, in inches?");
var BMI = (weight*703)/(height*height);
console.log("You have a BMI of " + Math.floor(BMI));
if (BMI<=15){
console.log("You are very severly underweight!");
}else if (BMI<16 && BMI>=15){
console.log("You are severly underweight!");
}else if (BMI<19 && BMI>=16){
console.log("You are underweight");
}else if (BMI<25 && BMI>=19){
console.log("You are healthy!");
}else if(BMI<30 && BMI >=25){
console.log("You are overweight" );
}else if(BMI<35 && BMI >=30){
console.log("You are moderately obese!");
}else{
console.log("lose weight fatty!");
}

Best way to provide a "tooltip tour" [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
What is the best way to provide a quick tour of a webapp using contextual tooltips?
Use case:
user navigates to the webapp
some form of popup asking if the user wants a guided tour of the interface
user can click next on each tooltip to be shown the next one
user can cancel the tour at any time by clicking some kind of exit X or button
Is there an easy library out there that does this?
Thanks!
The easiest way to do this is with Jeff Pickhardt's Guider-JS javascript tooltip walk-through library. It's very easy to use (although it has several very advanced features as well), and does exactly what you described.
You can check out this excellent example of a tooltip walk-through made with Guider-JS.
If you want to see a working example on a production site, it is used extensively on optimizely.com to provide help and walk-through guides for the user interface.
UPDATE: ZURB Foundation is now maintaining the excellent "Joyride" tooltip tour javascript library.
You could also write the tour part yourself using a linked list with an iterator that always calls a callback to set up the tooltip and one to close it. You can then use any tooltip script you want. Here's a quick proof of concept that should show you what I mean:
var toolTipList = {
tooltips: [],
currentTooltip: {},
addTooltip: function(tooltip){
var currentTail = this.tooltips.length > 0 ? this.tooltips[this.tooltips.length - 1] : {};
var newTail = {
tooltip: tooltip,
prev: currentTail
};
currentTail.next = newTail;
this.tooltips.push(newTail);
},
initialize: function(){
this.currentTooltip = this.tooltips[0];
this.currentTooltip.tooltip.callback();
},
next: function(){
if(this.currentTooltip.next){
this.currentTooltip.tooltip.close();
this.currentTooltip = this.currentTooltip.next;
this.currentTooltip.tooltip.callback();
}
}
};
for(var i = 0; i < 10; i++){
toolTipList.addTooltip({
callback: function(){
// called every time next is called
// open your tooltip here and
// attach the event that calls
// toolTipList.next when the next button is clicked
console.log('called');
},
close: function(){
// called when next is called again
// and this tooltip needs to be closed
console.log('close');
}
});
}
toolTipList.initialize();
setInterval(function(){toolTipList.next();}, 500);
​JSFiddle link

Categories

Resources