Make all elements in an array lowercase and remove whitespace - using jQuery - javascript

I have an array of postcodes that I have created by reading a text file. I would lik eto step through each item in the array and make it lowercase, and remove any whitespace. So far I have the following:
var postCodesCovered = new Array();
$.get('postcodes.txt', function(data){
postCodesCovered = data.split('\n');
});
$.each(postCodesCovered , function(){
$(this).toLowerCase().replace(/\s+/g, '');
});
This doesn't seem to do the trick though. Is it because I am not setting the values back to the array?

Since .get() is async you need to move your code in the success callback, and you don't need to use this.
var postCodesCovered;
$.get('postcodes.txt', function(data) {
postCodesCovered = data.split('\n');
$.each(postCodesCovered, function(index, value) {
postCodesCovered[index] = value.toLowerCase().replace(/\s+/g, '');
});
// Do something with the data here
});

#satpal is right - you need to process your list in the success callback. Each will iterate over the array items but you want to transform them into lowercase so map would be a better choice. Map takes an array and transforms each item returning a new array. See the jQuery.map docs for more info.
var postCodesCovered = [];
$.get('postcodes.txt', function(data) {
postCodesCovered = $.map(data.split('\n'), function(value, index) {
return value.toLowerCase().replace(/\s+/g, '');
});
});

ry this...
var postCodesCovered = new Array();
$.each(postCodesCovered , function(idx, val){
postCodesCovered[idx] = $(this).toLowerCase().replace(/\s+/g, '');
});

function convertArray(CapsArray){
lowcaseArray = [];
for (var i = 0; i <CapsArray.length; i++) {
lowcaseArray.push(CapsArray[i].replace(/\s+/g,"").toLowerCase());
}
return lowcaseArray;
}
The function above should do the job.
var YourLowCaseArray = convertArray(YourCapsArrayHere);

Related

How to store each value into one array?

Hi all I have problem to make some id into one array
Maybe you can help me...This image is the result
enter image description here
and this is my code
$.each(data.rows, function (i, ele) {
var tes = ele.ID;
console.log('ItemID', tes);
}
The Result that i want expect is each item in the one array like this 'ItemID = [22,2,43,2]'
const idArray = data.rows.map((r)=>r.ID)
//More verbose
const idArray = data.rows.map(function (ele){
return r.ID;
});
Map creates a loop through all the values in the array and uses the return of the function passed to create a new array.
EDIT:
I'm not sure I understand, you'd want an array of array?
const idArray = data.rows.map(function (ele){
return [r.ID];
});
var tempArray = []
$.each(data.rows, function (i, ele) {
tempArray.push(ele.ID);
}
// tempArray will be the solution
var data = [1,2,3,4]; // Assuming this array contains rows data
var resultArray = []; // Result array
var ids = data.map(function (ele){
return ele;
});
resultArray.push(ids.join(',')); // Join ids using "," separator
console.log(resultArray); // ["1,2,3,4"]

Remove duplicates in array separated by double commas in JavaScript

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>

JavaScript - Find and replace word in array

How would I find a word (in this case a placeholder, e.g _ORGAN_) in an array and replace it with an element's value?
sql = new Array();
$('#system').change(function(){
filter = " topography_index = _ORGAN_";
sql.push(filter);
});
In this case I would want to replace _ORGAN_ with $('#organ_menu').val();
Try this:
// sql array
var sql = ['organ not found', '_ORGAN_ is here'];
var val_to_replace = '_ORGAN_';
var replace_with = 'heart'; // temp value - change it with $('#organ_menu').val()
$.each(sql, function (key, val) {
// search for value and replace it
sql[key] = val.replace(val_to_replace, replace_with);
})
console.log(sql)
JSFiddle: http://jsfiddle.net/d8sZT/
You can simply do by iterating the array and then assign the value to once it find its match.
for (i = 0; i < sql.length; i++) {
if (sql[i] === "_ORGAN_") {
sql[i] = $('#organ_menu').val();
}
}
example fiddle for better understanding.
You can simply iterate over the array and use replace on each element
var organValue = $('#organ_menu').val();
for (var i = 0; i < sql.length; i++) {
sql[i] = sql[i].replace("_ORGAN_", organValue);
}
var regExp = new RegExp(organ, 'g');
$.each(sql, function(index, value) {
sql[index] = value.replace(regExp, 'test');
})
I'd try something like this, using replace:
sql = new Array();
$('#system').change(function(){
filter = " topography_index = _ORGAN_".replace("_ORGAN_", $('#organ_menu').val(), "gi");
sql.push(filter);
});
You can do this:
First find the index of the item:
var index=sql.indexOf("_ORGAN_");
Then insert your new item at that index and remove the first one:
sql.splice(index,1,newitem);
splice

How do I retrieve the first value from an array?

I have a call to a YouTube XML sheet that works perfectly fine. However, I am having trouble setting a value from one of the arrays. I want the first value from "songID" to be set as "first". I've tried doing this:
var first = songID[0]
but it only makes a new array with only the first character of each value... Any suggestions?
$(window).load(function(){
var pURL = 'http://gdata.youtube.com/feeds/api/playlists/F9183F81E7808428?v=2&alt=json&callback=?';
$.getJSON(pURL, function(data) {
$.each(data.feed.entry, function(i, item) {
var songID = item.media$group.media$content[0].url.substring(25, [36]);
var songTitle = item.title.$t;
var descript = item.media$group.media$description.$t;
var songAth = descript.slice(3);
}
}
})
You are already in an each() loop, so you shouldn't try to access it as an array, but just as a value. Just try:
if(i == 0){
var first = songID;
}
Are you sure what you're getting is actually an array? What makes you think that? Because if you ask for aString[0], you'll still get the first character back, because you can access string characters as if they're array elements. If it is indeed an array, just use var myString = myArray.join(""); and it'll become a string.
$(document).ready(function() {
var pURL = 'http://gdata.youtube.com/feeds/api/playlists/9002A5F66694EBA0?v=2&alt=json&callback=?';
$.getJSON(pURL, function(data) {
$.each(data.feed.entry, function(i, item) {
var songID = item.media$group.media$content[0].url.substring(25, [36]);
var songTitle = item.title.$t;
var descript = item.media$group.media$description.$t;
var songAth = descript.slice(3);
if(i==0){
alert("firstId is "+songID );
}
});
});
});
or just for first id:
var pURL = 'http://gdata.youtube.com/feeds/api/playlists/9002A5F66694EBA0?v=2&alt=json&callback=?';
$.getJSON(pURL, function(data) {
console.log(data.feed.entry[0].media$group.media$content[0].url.substring(25, [36]));
});
});

jquery split() issue

Hopefully this is easy for someone.
I have a set of checkboxes with values 1,2,3 etc with the same name attribute (cp_bundle).
I use the following code to get a comma-delimited list of those checkboxes.
var hl_calling_plan_bundle = $('input[name="cp_bundle"]:checked').getCheckboxVal() || "";
jQuery.fn.getCheckboxVal = function(){
var vals = [];
var i = 0;
this.each(function(){
vals[i++] = jQuery(this).val();
});
return vals;
}
if I check the first and third checkboxes, the following will be returned:
1,3
Then, I want to run a test to see whether a particular value (e.g. "3") exists in the the returned variable
But, I can't get past the split of the variable using the following:
var aCallingBundle = hl_calling_plan_bundle.split(",");
This gives the error:
hl_calling_plan_bundle.split is not a function
Any idea what's going on?
hl_calling_plan_bundle is an array. You have to use array operations on it, not string operations.
If you want to know if the value 3 is in the array, then you have to search the array for it. There are many ways to search an array, but since you have jQuery, it's easy to use the .inArray() function:
var index = $.inArray(3, hl_calling_plan_bundle);
if (index != 1) {
// found 3 in the array at index
}
Incidentally, you may want to simplify your function like this:
jQuery.fn.getCheckboxVal = function(){
var vals = [];
this.each(function(){
vals.push(this.value);
});
return vals;
}
or this way:
jQuery.fn.getCheckboxVal = function(){
return(this.map(function(){return(this.value)}).get());
}
split() is a String method, it does not exist on an Array.
When you say the following is returned 1,3, you may be implicitly calling the String's toString() method, which will by default join() the array members with a comma. If you explicitly called toString(), then you could call split(), but that would be an anti pattern.
You don't need to split the string, you can just use RegEx to search:
var str = '1,3,22,5';
/\b1\b/.test(str); // true
/\b2\b/.test(str); // false
/\b3\b/.test(str); // true
/\b5\b/.test(str); // true
/\b22\b/.test(str); // true
Making it a function:
String.prototype.findVal = function(val){
var re = new RegExp('\\b' + val + '\\b');
re.lastIndex = 0;
return re.test(this);
};
str.findVal(2); // false
str.findVal(22); // true
To get the checkboxes:
var cbs = document.getElementsByName('cp_bundle');
To get arrays of all values and the checked values:
var allValues = [];
var checkedValues = [];
for (var i=0, iLen=cbs.length; i<iLen; i++) {
if (cbs[i].checked) checkedValues.push(cbs[i].value);
allValues[i] = cbs[i].value;
}

Categories