How to splice item from array in javascript - javascript

I am looking a way to delete all elements from array if target object attribute is present in array.
var msg={name:'tar', type:'SR'}; //want to delete all object with type=SR
var items= [{name:'oh', type:'SR'},{name:'em', type:'PR'},
{name:'ge', type:'MR'},{name:'ohoo', type:'SR'}];
items.splice( items.indexOf(msg.type), 1 );
In this way only one object is deleting. Can someone suggest a better way that without using a loop i can delete all the target object from array

You can try something like following
items = items.filter(function(item){
return item.type !== msg.type;
});

a bit of functional and it's done:
var result = items.filter(function(item){
return (item.type == msg.type) ? false : true;
});

Related

Displaying only the first item from the localStorage data array

I am trying to build a board that should display the first number from the list but I can't find $.each alternative.
Currently, I have a piece of code that displays all items from the localStorage. Does anyone have an idea of jQuery function that would take an array as argument and callback only the first item? Similar to this one - $.each( array, callback ).
const clients = JSON.parse(localStorage.getItem("data"));
const odontologas = clients.Odontologas;
$.each(odontologas, function(i, item) {
if (item.Būsena === "Eilėje") {
$("#odontologasQueue").append(
`<p class="boardNumber">${item.EilėsNr}</p>`
);
} else {
$("#odontologasQueue").append(`<p class="boardNumber">000</p>`);
}
});
Just needed to add return false to if statement.
So either exit the loop when you find the match or use array.find
var first = odontologas.find(item => item.Būsena === "Eilėje")
// var first = odontologas.find(function(item) { return item.Būsena === "Eilėje" })
console.log(first)
Long story short, you want index of an entry? It's
odontologas.indexOf("Eilėje"); // equals -1 if element isn't found in the array

Cycling through jquery object to get its values

I have to loop through the object and get all its values. Here's an image of object
So, basically i have to get classificatorCodeId and loop through observationList to get its child classificatorCodeId's and observationLists, and so on.
If you guys have any ideas, what's the best way to loop through this object, id be happy to try your solutions.
Following code will print all values in that object as key --> value pairs
var traverse = function(mainObject)
{
$.each(mainObject, function(index, subObject)
{
if(($.type(subObject) === "object" || $.type(subObject) === "array"))
{
traverse(subObject);
}
else
{
console.log(index+" --> "+subObject);
}
});
}
traverse(mainObject);

Simplest way to remove duplicates from an array, whilst still keeping the last one

What would be the most simple way to remove duplicates from an array that have a specific value the same, whilst still keeping the most recent one pushed in?
Let's say I have this function.
bucket.bucketList =[];
bucket.addItem = function(item) {
bucket.bucketList.push(item);
}
The function pushes an object called foo this into the array on every mouse-scroll:
Some foo's also have a property ,
foo.name = "something";
The question is, what is the best way to delete a duplicate based on their property name whilst keeping the most recents one pushed in?
So the concept now is to remove all duplicates, except the last one, that have a foo.name = "example".
PS: I am using jQuery already in my project, so if jQuery has a more elegant way of doing this than vanilla JS i'd be more than happy to use it.
Edit: This is my exact code snippet:
bucket.addItem = function(item) {
bucket.bucketList.push(item);
var dict = {}, item;
for (var i = bucket.bucketList.length - 1; i >= 0 ; i--) {
item = bucket.bucketList[i];
if (item.name) {
// if already in the dict, remove this array entry
if (dict[item.name] === true) {
bucket.bucketList.splice(i, 1);
} else {
// add it to the dict
dict[item.name] = true;
}
}
}
}
Unfortunately, the above function removes all duplicates from the array that have the same name property. What I want is just to remove duplicates that have a SPECIFIC property name. e.g : item.name ="example"
Try this:
bucket.addItem = function(item) {
bucket.bucketList = bucket.bucketList.filter(function(e){
return item.name !== "example" || e.name !== "example"
});
bucket.bucketList.push(item);
}
This basically removes all items that have the same name as the current item, then pushes the current item onto the list, but only if the name is "example"

Equivalent of underscore.js's find in jquery

How to do the equivalent of this in jquery?
var myCollection = $(".sortable");
var link = _.find(myCollection, function(item){
return someInput.value == $(item).data("sort-column");
});
Knowing why you're trying to do this would help, but I don't think there's a built in function to replace for the underscore one. One of the comments mentions filter, but that is not the same as underscore's _.find, since find returns for the first found element.
That's the only suggestion I have, but that's just a forEach
var item
$.each(myCollection,function( index, element ) {
if ( condition ) {
item = element
return false
}
});
You can use $.grep
Finds the elements of an array which satisfy a filter function. The original array is not affected.
https://api.jquery.com/jQuery.grep/
var link = $(".sortable[data-sort-column=" + someInput.value + "]");
Have you looked at jQuery's each?
You might format it more like:
myCollection.each(function( item ) { ... });

Build a switch based on array

I want to create a Javascript switch based on an array I'm creating from a query string. I'm not sure how to proceed.
Let's say I have an array like this :
var myArray = ("#general","#controlpanel","#database");
I want to create this...
switch(target){
case "#general":
$("#general").show();
$("#controlpanel, #database").hide();
break;
case "#controlpanel":
$("#controlpanel").show();
$("#general, #database").hide();
break;
case "#database":
$("#database").show();
$("#general, #controlpanel").hide();
break;
}
myArray could contain any amount of elements so I want the switch to be created dynamically based on length of the array. The default case would always be the first option.
The array is created from a location.href with a regex to extract only what I need.
Thanks alot!
#Michael has the correct general answer, but here's a far simpler way to accomplish the same goal:
// Once, at startup
var $items = $("#general,#controlpanel,#database");
// When it's time to show a target
$items.hide(); // Hide 'em all, even the one to show
$(target).show(); // OK, now show just that one
If you really only have an array of selectors then you can create a jQuery collection of them via:
var items = ["#general","#controlpanel","#database"];
var $items = $(items.join(','));
Oh, and "Thanks, Alot!" :)
I think you want an object. Just define keys with the names of your elements to match, and functions as the values. e.g.
var switchObj = {
"#general": function () {
$("#general").show();
$("#controlpanel, #database").hide();
},
"#controlpanel": function () {
$("#controlpanel").show();
$("#general, #database").hide();
},
"#database": function () {
$("#database").show();
$("#general, #controlpanel").hide();
}
}
Then you can just call the one you want with
switchObj[target]();
Granted: this solution is better if you need to do explicitly different things with each element, and unlike the other answers it focused on what the explicit subject of the question was, rather than what the OP was trying to accomplish with said data structure.
Rather than a switch, you need two statements: first, to show the selected target, and second to hide all others.
// Array as a jQuery object instead of a regular array of strings
var myArray = $("#general,#controlpanel,#database");
$(target).show();
// Loop over jQuery list and unless the id of the current
// list node matches the value of target, hide it.
myArray.each(function() {
// Test if the current node's doesn't matche #target
if ('#' + $(this).prop('id') !== target) {
$(this).hide();
}
});
In fact, the first statement can be incorporated into the loop.
var myArray = $("#general,#controlpanel,#database");
myArray.each(function() {
if ('#' + $(this).prop('id') !== target) {
$(this).hide();
}
else {
$(this).show();
}
});
Perhaps you're looking for something like this? Populate myArray with the elements you're using.
var myArray = ["#general","#controlpanel","#database"];
var clone = myArray.slice(0); // Clone the array
var test;
if ((test = clone.indexOf(target)) !== -1) {
$(target).show();
clone.splice(test,1); // Remove the one we've picked up
$(clone.join(',')).hide(); // Hide the remaining array elements
}
here you dont need to explicitly list all the cases, just let the array define them. make sure though, that target exists in the array, otherwise you'll need an if statement.
var target = "#controlpanel";
var items = ["#general","#controlpanel","#database"];
items.splice($.inArray(target, items), 1);
$(target).show();
$(items.join(",")).hide();
items.push(target);

Categories

Resources