Javascript/Jquery Convert string to array - javascript

i have a string
var traingIds = "${triningIdArray}"; // ${triningIdArray} this value getting from server
alert(traingIds) // alerts [1,2]
var type = typeof(traingIds )
alert(type) // // alerts String
now i want to convert this to array so that i can iterate
i tried
var trainindIdArray = traingIds.split(',');
$.each(trainindIdArray, function(index, value) {
alert(index + ': ' + value); // alerts 0:[1 , and 1:2]
});
how to resolve this?

Since array literal notation is still valid JSON, you can use JSON.parse() to convert that string into an array, and from there, use it's values.
var test = "[1,2]";
parsedTest = JSON.parse(test); //an array [1,2]
//access like and array
console.log(parsedTest[0]); //1
console.log(parsedTest[1]); //2

Change
var trainindIdArray = traingIds.split(',');
to
var trainindIdArray = traingIds.replace("[","").replace("]","").split(',');
That will basically remove [ and ] and then split the string

Assuming, as seems to be the case, ${triningIdArray} is a server-side placeholder that is replaced with JS array-literal syntax, just lose the quotes. So:
var traingIds = ${triningIdArray};
not
var traingIds = "${triningIdArray}";

check this out :)
var traingIds = "[1,2]"; // ${triningIdArray} this value getting from server
alert(traingIds); // alerts [1,2]
var type = typeof(traingIds);
alert(type); // // alerts String
//remove square brackets
traingIds = traingIds.replace('[','');
traingIds = traingIds.replace(']','');
alert(traingIds); // alerts 1,2
var trainindIdArray = traingIds.split(',');
​for(i = 0; i< trainindIdArray.length; i++){
alert(trainindIdArray[i]); //outputs individual numbers in array
}​

Related

How to remove partial duplicate values in jquery array

I have a single level array of key/value pairs, like this:
var user_filters= ['color=blue', 'size=small', 'shape=circle', 'size=large', 'shape=square']
I need a function to perform the following:
find all duplicate keys
replace the first occurrence of the key/value pair with the second occurrence
delete the second occurrence
In this case, it would produce the following result:
user_filters= ['color=blue', 'size=large', 'shape=square']
Something like...
function update_array(){
$.each(user_filters, function(i){
var key = this.split('=')[0];
if(key is second occurrence in user_filters)
{
var index = index of first occurrence of key
user_filters[index] = user_filters[i];
user_filters.splice(i,1);
}
});
}
What is the best way to do this? Thanks!
I would keep the data in an object and this way any duplicate will automatically overwrite the previous entry..
See this for example:
var user_filters= ['color=blue', 'size=small', 'shape=circle', 'size=large', 'shape=square'];
var object = {};
for (var i = 0; i < user_filters.length; i++) {
var currentItem = user_filters[i].split('=');
var key = currentItem[0];
var value = currentItem[1];
object[key] = value;
}
console.log(object);
You can use a hash object to get the key-value pairs without duplicates and then transform the hash object back into an array like this:
function removeDuplicates(arr) {
var hash = arr.reduce(function(h, e) {
var parts = e.split("=");
h[parts[0]] = parts[1];
return h;
}, {});
return Object.keys(hash).map(function(key) {
return key + "=" + hash[key];
});
}
var user_filters = ['color=blue', 'size=small', 'shape=circle', 'size=large', 'shape=square'];
console.log(removeDuplicates(user_filters));
You could use a Map which does the unique/overriding automatically, and is able to get you an array back in case you need it
var user_filters= ['color=blue', 'size=small', 'shape=circle', 'size=large', 'shape=square'];
var m = new Map(user_filters.map(v => v.split("=")));
console.log([...m.entries()].map(v => v.join("=")));
It would be better to iterate from back of array ,
thus for every unique key you need to keep a variable true or false (initially false).
so if true mean already occurred so deleted it else keep it and make its variable true .
It is much more better approach then your current . you don't have to keep last index and swapping then deleting.
You may convert to json and then back to the array format you want . IN the below code you get the result object in the format you want.
var user_filters= ['color=blue', 'size=small', 'shape=circle', 'size=large', 'shape=square'];
function toJson(obj){
var output = {};
$.each(obj, function(i){
var keyvalPair = this.split('=')
var key = keyvalPair[0];
output[key]= keyvalPair[1];
});
return output;
}
function toArray(obj){
var output = [];
$.each(obj, function(i){
output.push(i+"="+obj[i]);
});
return output;
}
var result = toArray(toJson(user_filters));
console.log(result);

javascript onBlur to to avoid duplicate string

In my project I need onBlur event to check string have contain any duplicate character to remove it i.e text value has 01,02,04,01,07,2 in the String after the comma 01 has to duplicate value so I need 01,02,04,07,2. Is this possible?
$("input:text").on('blur', function() {
var textVal = $(this).val();
var valArray = textVal.split(',');
var newValArray = [];
for(var i in valArray) {
if(newValArray.indexOf(i) === -1) {
newValArray.push(i);
}
}
var newTextVal = newValArray.join();
$(this).val(newTextVal);
})
Using JQuery you could do that
var numberString = '01,02,04,01,07,2';
var result = [];
$.each(numberString.split(','), function(index, number) {
if($.inArray(number, result) === -1) {
result.push(number);
}
});
document.write(result.join(','));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can use the split(",") method to create an array of the values and then loop through the array values and then use splice(0,1) method to remove the duplicate. After that you can revert the array back to a string using the join(",") method to create the string with the comma delimiter.
I wrote this reduce codes. It does what you need.
//I altered your number string to this.
var numberString = '01,02,04,01,07,2,07,10,55,55,10,02,500,450';
var strDedoop = function ( str ) {
var strArr = [], // temp array
numStrSplit = str.split(','); // split the number string by comma
//loop through the array
numStrSplit.forEach(function(currentValue) {
// Ternary operation. If the number is not in the array it is put in.
strArr.indexOf(currentValue) === -1 ? strArr.push(currentValue) : false;
});
return strArr.toString(); // return the array as a string.
}
strDedoop(numberString);
// returns "01,02,04,07,2,10,55,500,450"
You can use it this way.
$("input:text").on('blur', strDedoop(numberString));

How to add string to array?

Example:
var imageBounds = [[40.712216, -74.22655], [46.773941, -79.12544]];
I need to create same from js. The problem that I am getting data in string format:
[40.712216, -74.22655], [46.773941, -79.12544]
so:
var mystr = "[40.712216, -74.22655], [46.773941, -79.12544]"
Ok, lets create empty array:
var myarr = []; // empty array
but how to add data to it? I know about push method but it's work only with arrays, and I have got text.
Make it valid JSON (by adding [ at beginning and ] at ending) afterward parse the string using JSON.parse method.
var mystr = "[40.712216, -74.22655], [46.773941, -79.12544]";
var res = JSON.parse('[' + mystr + ']');
console.log(res);

javascript comma separated list to array

I have this type of list from javascript:
Amila,Asanka,Imaad,Kelum,Lakshan,Sagara,Thilina
I used the following code to convert to my output
var array = columnsload.split(",");
var string = JSON.stringify(columnsload);
var nameArray = string.split(',');
The output is like this :
"Amila,Asanka,Imaad,Kelum,Lakshan,Sagara,Thilina"
But I really need it like this :
["Amila","Asanka","Imaad","Kelum","Lakshan","Sagara","Thilina"]
Anyone know how to get output like this?
the split function is enough to convert the string into an array;
var names = "Amila,Asanka,Imaad,Kelum,Lakshan,Sagara,Thilina";
var nameArr = names.split(",");
console.log( nameArr );
http://www.w3schools.com/jsref/jsref_split.asp
Just do var nameArray = columnsload.split(',');. You dont need to stringify the array and then split it again, just one .split would be enough.
var columnsload = "Amila,Asanka,Imaad,Kelum,Lakshan,Sagara,Thilina";
var nameArray = columnsload.split(',');
console.log(nameArray);
If you need the whole thing to be string, you can run a JSON.stringify on the array after.
var columnsload = "Amila,Asanka,Imaad,Kelum,Lakshan,Sagara,Thilina";
var nameArray = columnsload.split(',');
console.log(JSON.stringify(nameArray));
// outputs ["Amila","Asanka","Imaad","Kelum","Lakshan","Sagara","Thilina"]
// as one string.

key-value pair undefined in javascript

For some reason I have a string like this:
"id: 123, title: something, category: science, ... "
To make a javascript object containing the key-value pairs I wrote the following method:
function stringToMap(stringToCut){
var map = {};
var listOfPairs = stringToCut.split(",");
for(var i = 0; i < listOfPairs.length; i++){
var pair = listOfPairs[i].split(":");
map[pair[0]] = pair[1];
}
return map;
}
it's important to access it with dot, not with [] brackets.
In chrome debug mode I see the expected object, but when I want to access one of it's element, like:
console.log(obj.title);
I get undefined...
What Am I doing wrong?
It's because there's a space in your key name:
console.log(obj[" title"]); // "something"
To fix this, change your first split to split on ", " instead of just ",":
var listOfPairs = stringToCut.split(", ");
JSFiddle demo.
As a further fix, you'll also want to change your second split to split on ": " rather than just ":", otherwise all your values will begin with spaces.
var pair = listOfPairs[i].split(": ");

Categories

Resources