I have a list like this in a div:
<div id="x">5,2,3,1,4,9,8</div>
How do I simply remove a given element from this list?
JQuery or JavaScript may be used.
Please note that the numbers in the list are unique and they are coming in from a database of type int(11), they are not in any sort of order.
Any help appreciated guys...
First, get the text:
var text=$("#x").text();
Then split it:
var items=text.split(',');
If there's no items, you'll have an empty string as the only element of the array. If so, empty the array:
if(items.length==1&&items[0]=="") {
items=[];
}
Now convert everything to an integer: (note that this step isn't actually required, but if you're doing anything else with items, it's nice to have)
items=items.map(function(str) { return parseInt(str, 10); });
Put the item you want to remove in a variable:
var itemToRemove=3;
Find that in the array:
var index=items.indexOf(itemToRemove);
If it was found, splice it out of the array:
if(index!==-1) {
items.splice(index, 1);
}
Join the items back together:
text=items.join(',');
Put it back in the element:
$("#x").text(text);
Try this with toRemove equal to 5, 3, or 8 to see that it works for all cases:
var toRemove = 3; // the number you want to remove
$('#x').text($('#x').text().replace(new RegExp(toRemove + ',?'
+ '|,?' + toRemove + '$'), ''));
See example →
Using jQuery's grep-method may be an option too:
var toRemove=1;
$('#x').text( $.grep($('#x').text().split(','),
function (a) { return a != toRemove; }).join(','));
To remove multiple items:
var toRemove=[1,8,3];
$('#x').text( $.grep($('#x').text().split(','),
function (a) { return $.inArray(Number(a),toRemove)<0; })
.join(','));
(But I would prefer a RegExp-solution, it should be much faster)
This is a simple solution that just requires jquery.
function removeFromDiv(which)
{
var data = $("#x").html();
data_arr = data.split(",");
for (var i = 0; i < data_arr.length; i++)
{
if (data_arr[i] == which)
{
data_arr.splice(i, 1);
data = data_arr.join(",");
}
}
$("#x").html(data);
}
then simply run:
removeFromDiv("4");
Doesn't really need to be much harder than this:
function removeIndexFromX(index) {
// Build array from comma-delimited content
var arr = $("#x").text().split(',');
// Remove index (zero-based)
arr.splice(index, 1);
// Replace
$("#x").text(arr.join(','));
}
function removeNumberFromX(num) {
var arr = $("#x").text().split(',');
for (var i = 0; i < arr.length; i++) {
if (arr[i] === num) {
arr.splice(i, 1);
}
}
$("#x").text(arr.join(','));
}
The benefit of split and join is that you can use those to manage delimiters (e.g. commas) for you.
Related
I'm looking to extract the values 'adult' and '2ndclass' from this custom javascript array in separate javascript variables for each value. Anyone has any ideas on how to do this?
In the following case, there are 2 products added to cart but I would like to have the flexibility to always grab any existing values for each product that is added to cart regardless of the amount added. Is that possible?
[
'pass/DE-NO-RS-BE-FI-PT-BG-DK-LT-LU-HR-LV-FR-HU-SE-SI-ME-SK-GB-IE-MK-EE-CH-GR-IT-ES-AT-CZ-PL-RO-NL-TR-BA/**adult/2ndclass**',
'pass/DE-NO-RS-BE-FI-PT-BG-DK-LT-LU-HR-LV-FR-HU-SE-SI-ME-SK-GB-IE-MK-EE-CH-GR-IT-ES-AT-CZ-PL-RO-NL-TR-BA/**youth/2ndclass**'
]
Thank you in advance for your help
You can also use RegExp to get those values out.
var arr = [
"pass/DE-NO-RS-BE-FI-PT-BG-DK-LT-LU-HR-LV-FR-HU-SE-SI-ME-SK-GB-IE-MK-EE-CH-GR-IT-ES-AT-CZ-PL-RO-NL-TR-BA/**adult/2ndclass**",
"pass/DE-NO-RS-BE-FI-PT-BG-DK-LT-LU-HR-LV-FR-HU-SE-SI-ME-SK-GB-IE-MK-EE-CH-GR-IT-ES-AT-CZ-PL-RO-NL-TR-BA/**youth/2ndclass**"
];
var results = [];
for (var i=0; i < arr.length; i++) {
var matches = arr[i].match(/\*\*(.+)\/(.+)\*\*/);
if(matches && matches.length >= 3)
results.push([matches[1], matches[2]]);
}
console.log(results);
You can try the code here https://jsfiddle.net/p84eftL7/1/
First of all i didn't get your question completely. But as far as i can understand you want those 2 values at the end of the strings from an array. You can try something like this
var a, b;
for(s in YOUR_ARRAY){
[...other, a, b] = YOUR_ARRAY[s].split("/");
console.log(a, b);
//Do whatever you want to do with a,b
}
Let me explain myself, Firstly you would require to iterate over your array thats why we have a 'for' loop here. Then for each string which is given by 'YOUR_ARRAY[s]' you are splitting the string with '/' as a delimiter. Rest of the thing is pretty simple.
For your reference go through these links
https://www.w3schools.com/js/js_loop_for.asp
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
UPDATE:
As mentioned in the comments. If you want to have a function for this then
function processValues(arr){
var a, b;
for(s in arr){
[...other, a, b] = arr[s].split("/");
console.log(a, b);
//Do whatever you want to do with a,b
}
}
processValues(YOUR_ARRAY);
In the end what I did was the following
As I had to reference back to the name of the variable I used the following to slice up the array so I could reference that using index numbers for the values I needed to retrieve:
function() {
var myStringArray = {{MY_ARRAY}};
var arrayLength = myStringArray.length;
var output = []
for (var i = 0; i < arrayLength; i++) {
var string = myStringArray[i].split("/",4)
/*pull index 2 and 3 from string and convert to string*/
output.push(string)
}
return output
}
After that I had to loop the new array that was being pushed out of the info as mentioned above
Since I only needed to split up particular indices from that NEW_ARRAY_2, I used the following to do that
function() {
var products = {{NEW_ARRAY_2}};
var arr = []
for (var i=0; i < products.length; i++) {
var prod = products[i];
var matches = prod[2];
arr.push(matches);
}
var list = arr.join(', ')
return list
}
SAMPLE RETURN for 2 products: 'adult, youth'
Thank you for your support
I have an array in JavaScript like this
var data = [,A_1_VII,VII,V2,,A_1_VII,VII,V2,,A_1_VII,VII,V2,,B_1_XIV,XIV,V3,,B_2_XVI,XVI,V3]
when I alert in JavaScript it gives as below
,A_1_VII,VII,V2
,A_1_VII,VII,V2
,A_1_VII,VII,V2
,B_1_XIV,XIV,V3
,B_2_XVI,XVI,V3
But I want like this which is duplicates removed array
var unique_data = [,A_1_VII,VII,V2,,B_1_XIV,XIV,V3,,B_2_XVI,XVI,V3]
On alert it should give like this
,A_1_VII,VII,V2
,B_1_XIV,XIV,V3
,B_2_XVI,XVI,V3
First Thing your array contains string as a constant that's not going to work.
Secondly, if all of you value are strings you can do it as follows:
var data =[,"A_1_VII","VII","V2",,"A_1_VII","VII","V2",,"A_1_VII","VII","V2",,"B_1_XIV","XIV","V3",,"B_2_XVI","XVI","V3"];
var uniqueArray = data.filter(function(item, pos) {
return data.indexOf(item) == pos;
})
alert(uniqueArray);
Assuming the variables in your array are well defined, you can clean it up and remove duplicates with a for loop:
var data [/* ... */];
var unique_data = [];
for(let i = 0; i < data.length; i++) {
if (data[i] && unique_data.indexOf(data[i]) === -1) {
unique_data.push(data[i]);
}
}
Please note that the code above assumes that your array contains non-object types, otherwise the solution would need to use something more sophisticated than indexOf().
You can create your unique function to remove duplicate entry and empty value from array like this.
var data =[,"A_1_VII,VII","V2,,A_1_VII","VII","V2",,"A_1_VII","VII","V2",,"B_1_XIV,XIV","V3",,"B_2_XVI,XVI,V3"]
var unique_data = uniqueList(data);
alert(unique_data);
function uniqueList(list) {
var uniqueResult = [];
$.each(list, function(i, e) {
if ($.inArray(e, uniqueResult) == -1 &&$.inArray(e, uniqueResult)!="")// chech for unique value and empty value
uniqueResult.push(e);
});
return uniqueResult ;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
My problem is as follows: I am trying to take data as formatted in the 'names' variable in the snippet below, convert the string to array, then reorganize the array so the text is in the correct order. I am able to get the pieces I have put together to properly sort the first or last instance of a first & last name, but am seeking guidance on how to go about processing multiple names. The snippet below will return the last instance of the first & last name in the correct order. At this point, I am only looking to have the data returned as a properly sorted array, e.g.
if the input string is
names = "Bond, James & Banner, Bruce";
once processed should return: ['James', 'Bond,', '&', 'Bruce', 'Banner,']
As always I appreciate all the help I can get, thanks in advance!
Array.prototype.move = function(from,to){
this.splice(to,0,this.splice(from,1)[0]);
return this;
};
var names ="Bond, James & Banner, Bruce";
var namesArr = names.split(' ');
var idx;
// search for a comma (only last names have commas with them)
for(var i = 0; i < namesArr.length; i++) {
if(namesArr[i].indexOf(',') != -1) {
idx = i;
}
}
namesArr.move(idx, idx+1);
console.log(namesArr);
You were close but this solution should work for you. Basically you need to update in the loop and increment the index i to account for the switch. Otherwise you will end up revisiting the first last name you switch.
Array.prototype.move = function(from,to){
this.splice(to,0,this.splice(from,1)[0]);
return this;
};
var names ="Bond, James & Banner, Bruce & Guy, Other";
var namesArr = names.split(' ');
var idx;
// search for a comma (only last names have commas with them)
for(var i = 0; i < namesArr.length; i++) {
if(namesArr[i].indexOf(',') != -1) {
namesArr.move(i, i+1);
i++;
}
}
console.log(namesArr);
Another solution could be by using String.prototype.match() and a regular expression \w+ to match the names:
var names = "Bond, James & Banner, Bruce & Licoln, Anna"; // ...
var arr_names = names.match(/\w+/g); // Match names
var res = [];
for (var i = 0; i < arr_names.length; i += 2) { // Step by 2
res.push(arr_names[i + 1]); // Push the name before
res.push(arr_names[i]); // Push the current name
res.push("&"); // Add "&"
}
res.splice((res.length - 1), 1); // Remove last "&"
console.log(res);
I have an object and an array of categories that should be kept in the object. This snip https://jsfiddle.net/h10rkb6s/2/ ( see log ) works but I cant seems to shake the idea that it is to complicated for a simple search and keep task.
var thz_icon_source = {"Spinners":["spinnericon1","spinnericon2"],"Awesome":["awesomeicon1","awesomeicon2"],"Others":["othericon1","othericon2"]};
var $categories = '["Spinners","Awesome"]';
var $CatsArray = JSON.parse($categories);
var groups = [];
for(var k in thz_icon_source) groups.push(k);
$.each($CatsArray,function(i,keep){
var index = groups.indexOf(keep);
if (index !== -1) {
groups.splice(index, 1);
}
});
for (var i = 0; i < groups.length; i++) {
delete thz_icon_source[groups[i]];
}
I tried with
$.each(thz_icon_source,function(category,icons){
$.each($CatsArray,function(i,keep){
var index = category.indexOf(keep);
if (index !== -1) {
delete thz_icon_source[category];
}
});
});
but this works only if 1 item is inside my search array.
Any help is appreciated.
There's no need to iterate over $CatsArray to find out which ones should be deleted. You will need to iterate over the keys of the object, and find out for each of them whether it should be deleted, to filter by that.
Leaving the top 3 lines of your script intact, you could simplify to
var keysToDelete = Object.keys(thz_icon_source).filter(function(groupName) {
return $CatsArray.indexOf(groupName) == -1;
});
($.grep would be the jQuery-ism for the filter method, if you are into that).
But assuming we don't even need those groups in an array, you could simply do
for (var groupName in thz_icon_source)
if ($CatsArray.indexOf(groupName) == -1)
delete thz_icon_source[groupName];
However, instead of deleting items from that object, I'd recommend to create a new object with only those that you want to keep. It's much easier to use:
var kept = {};
for (var i=0; i<$CatsArray.length; i++)
kept[$CatsArray[i]] = thz_icon_source[$CatsArray[i]];
I'm a beginner with javascript, and after searching I am still running into an error with this part of my code.
I have an array:
var choices = [ '$5/hr', '$6/hr', '$7/hr', '$10/hr' ];
And I want to use a regular expression to return the array as integers so I can use it for further calculations. I know that replace only works on strings and not an array so I have tried the following:
// Strip other characters and return only integers.
for (var i = 0; i < choices.length; i++) {
choices[i] = choices[i].replace(/[^0-9.]/g, '');
}
EDIT: Apparently the issue is somewhere else in my code. Maybe this needs to be wrapped in another function?
Here is the function that this resides in. This function receives an array as a value and will calculate an average using the array received and the choices array which I cannot convert to integers.
// Choice values
var ul = document.getElementById('Results');
var choices = [];
// Get li element choices
for (var i = 0; i < ul.childNodes.length; i++) {
if (ul.childNodes[i].nodeName == "LI") {
choices.push(ul.childNodes[i]);
}
}
// Strip the last element in array since it is the result container.
choices.splice(-1,1);
// Strip other characters and return only integers.
for (var i = 0; i < choices.length; i++) {
choices[i] = choices[i].replace(/[^0-9.]/g, '');
}
Thanks!
The issue is that you are pushing the nodes in your array, not their text content. Try this instead:
choices.push(ul.childNodes[i].textContent)
or:
choices.push(ul.childNodes[i].childNodes[0].nodeValue)