Related
I want all index value that have data in array after ":" & split it to different Array at same index number. I am able to change data for one index value but its not changing for all value
var Array = ["Alice:", "John:654", "Bob:123"];
** After Split **
var Array = ["Alice:", "John:", "Bob:"];
var new array = ["", "654", "123"];
<script>
var array = ["Alice:", "John:654", "Bob:123"];
var el = array.find(a =>a.includes(":"));
let index = array.indexOf(el);
const newArray = el.split(':')[0] + ':';
var array2 = ["", "", ""];
array2[index] = newArray;
document.getElementById("demo").innerHTML = "The value of arry is: " + el;
document.getElementById("demo2").innerHTML = "The index of arry is: " + index;
document.getElementById("demo3").innerHTML = "split value: " + newArray;
document.getElementById("demo4").innerHTML = "new arr: " + array2;
</script>
If I understood your question correctly, this should be a solution:
const [oldOne, newOne] = array.reduce(
(acumm, current, index) => {
const [name, value] = current.split(':');
acumm[0].push(`${name}:`);
acumm[1].push(value ?? '');
return acumm;
},
[[], []]
);
Stackblitz Example
Info
// not mess up global vars, "Array" is a constructor
var Array = ["Alice:", "John:654", "Bob:123"];
** After Split **
var Array = ["Alice:", "John:", "Bob:"];
// not mess up with key words, "new" can only be called on
// constructors and array is as far i know not one
var new array = ["", "654", "123"];
Here's a solution using .map (so you don't need to keep track of the index)
var array = ["Alice:", "John:654", "Bob:123"];
var result = array.map(e => e.split(":")[1])
array = array.map(e => e.split(":")[0] + ":")
console.log(array, result)
Note that split(":")[1] will only give you the first entry if you have multiple ":" in the values, eg "John:654:999" - you can combine them with splice and join, eg:
parts.splice(1).join(":")
Here's the same solution, using a forEach if you prefer a single iteration over two:
var array = ["Alice:", "John:654:999", "Bob:123"];
var result = [];
var replacement = [];
array.forEach(e => {
var parts = e.split(":");
replacement.push(parts[0] + ":")
result.push(parts.splice(1).join(":"))
});
console.log(replacement, result)
Input Array:
["a,b,c", "foo,bar", "1,2,1", "a"] // should convert to → '"a,b,c","foo,bar","1,2,1","a"'
Now, using toString() or .join("") will produce the unwanted:
var arr = ["a,b,c", "foo,bar", "1,2,1", "a"];
console.log( arr.toString() )
console.log( arr.join(',') )
So, to bypass that, the first which comes to mind is JSON.stringify:
var arr = ["a,b,c", "foo,bar", "1,2,1", "a"];
var s = JSON.stringify(arr).slice(1,-1);
console.log( typeof s, ":" , s )
↑ The above is the wanted result, but i'm sure there's a cleaner way of doing it
Question:
Is this the only way to convert an Array which has string items containing commas to a String?
Here is another way to get the same result as with stringify (except when arr contains strings with embedded double-quotes):
arr.reduce((a, c, i) => a + (i > 0 ? ',"' : '"') + c + '"', '')
It depends on what "converting to string" means to you. An array is an ordered list of items numerically accessed. A string is a textual representation of that ordered list. If your question is "how to convert an array to a string while still being able to get the original array back," then the most performant answer would be JSON.stringify to convert the Array to a String, then JSON.parse to convert the string back into an array. However, JSON.stringify is only one of the many ways you could convert an array to a string.
A simple way to join all the strings in the array together is either by using Array.prototype.join.call or String.prototype.concat.apply
"use strict";
(function(){
var arr = ["a,b,c", "foo,bar", "1,2,1", "a"];
console.log( "Array.prototype.join: ", arr.join("") );
console.log( "String.prototype.concat: ", String.prototype.concat.apply("", arr) );
})();
Another way you could convert an array to a string is by going through each string in the array and concatenating them together.
"use strict";
(function(){
var arr = ["a,b,c", "foo,bar", "1,2,1", "a"];
var res = "";
var i = arr.length;
var curStr = "";
while (i--) {
curStr = arr[i];
// when the item on the left side is a string, the "+"
// operator acts as a concatination operator
res = res + curStr + ",";
// res += curStr + ","; // works just as well
// res += arr[i] + ","; // also works too
}
console.log( res );
})();
Using the fact that we can go through each item in the array, and look at each string individually, we can do something like converting each string to a base64 blob, then joining each string with a line break.
"use strict";
(function(window){
var btoa = window.btoa, atob = window.atob;
function encode(theArray){
var i = theArray.length, res = "";
while (i--) res += btoa(theArray[i]) + "\n";
return res.slice(0,-1);
}
function decode(theString){
var splitted = theString.split("\n");
var i = splitted.length, res = [];
while (i--) res.push( atob(splitted[i]) );
return res;
}
var arr = ["a,b,c", "foo,bar", "1,2,1", "a"];
var encoded_arr = encode(arr);
console.log("encoded_arr: ", JSON.stringify(encoded_arr, null, 1).replace(/\\n/g, "\n") );
var decoded_arr = decode(encoded_arr);
console.log( "decoded_arr", JSON.stringify(decoded_arr, null, 1).replace(/\\n/g, "\n") );
})(self);
There are countless more ways to join an array of strings together depending on your specific needs. Below are many such examples. Please emphasize that while all the following "work", none of them are as efficient as Array.prototype.join.
String.prototype.replace
function joinWithRegexp(str1, str2) {
return str1.replace(new RegExp("$"), str2);
}
console.log(joinWithRegexp("Foo", " bar"));
String.prototype.padStart
function joinWithPadStart(str1, str2) {
return str2.padStart(str1.length + str2.length, str1);
}
console.log(joinWithPadStart("Foo", " bar"));
String.prototype.padEnd
function joinWithPadEnd(str1, str2) {
return str1.padEnd(str1.length + str2.length, str2);
}
console.log(joinWithPadEnd("Foo", " bar"));
Template Literals
function joinWithTemplateLiteral(str1, str2) {
return `${str1}${str2}`;
}
console.log(joinWithTemplateLiteral("Foo", " bar"));
DOM
var tmpElement = document.createElement("div");
function joinWithDOM(str1, str2) {
tmpElement.appendChild(document.createTextNode(str1));
tmpElement.appendChild(document.createTextNode(str2));
return tmpElement.textContent;
}
console.log(joinWithDOM("Foo", " bar"));
Blob
var reader = new FileReader;
function joinWithBlob(str1, str2, thenFunc) {
reader.onload = function(){ thenFunc( reader.result ); };
reader.readAsText(new Blob([str1, str2]));
}
joinWithBlob("Foo", " bar", function(result){
console.log(result);
});
Trying to convert comma-separated string to array w/ quotes around each value in js:
var ipd = 'field1,field2';
console.log('Img Pad string: ' + ipd); // field1,field2
var ipdarray = new Array();
ipdarray = ipd.split(',');
console.log('Img Pad array split: ' + typeof ipdarray); // object
console.log('Img Pad array: ' + ipdarray); // field1,field2
I want the array to be: ["field1","field2"]
Tried to follow this: Convert comma separated string to array
but it's not converting to an array.
It is being converted to an array, but when you output the string (in console.log), the array is being coerced back into that string syntax because of the + operator (acting as a concatenator).
Here is a more isolated example of what is happening:
var string = 'field1,field2';
var arr = string.split(',');
console.log(Array.isArray(arr));
console.log(arr.length);
//When using the +, it will coerce into a string
console.log('Coerce to string ' + arr);
//When passing the array as an argument, it will stay an array
console.log('Stays and array', arr);
In order to preserve the array literal syntax, you'll need to JSON.stringify the array before outputting it if you want to use the + operator, or you can just output the array as a separate argument to console.log
JSON.stringify(ipdarray);
See it in action:
var ipd = 'field1,field2';
console.log('Img Pad string: ' + ipd); // field1,field2
var ipdarray = new Array();
ipdarray = ipd.split(',');
console.log('Img Pad array split: ' + typeof ipdarray); // object
console.log('Img Pad array: ' + JSON.stringify(ipdarray)); // ["field1","field2"]
// OR
console.log('Img Pad array: ', ipdarray); // ["field1","field2"]
Also, arrays are "object"s, but there are other ways to determine if that "object" is an instance of an array:
var arr = [];
console.log(typeof arr);
console.log(arr instanceof Array)
console.log(Array.isArray(arr));
Given input string you can use String.prototype.match() with RegExp /[^,]+/g to match one or more characters which are not comma ,
var ipd = 'field1,field2';
var ipdarray = ipd.match(/[^,]+/g);
Note that + operator converts array to string at
console.log('Img Pad array: ' + ipdarray); // field1,field2
use comma , operator at console.log() call
console.log('Img Pad array: ', ipdarray); // field1,field2
var a = "field1,field2"
var b = a.split(',');
var c = b.map(function (v) {
return '"' + v + '"';
})
console.log(c);
console.log(c[0]);
console.log(c[1]);
I'm trying to iterate over a "value" list and convert it into a string. Here is the code:
var blkstr = $.each(value, function(idx2,val2) {
var str = idx2 + ":" + val2;
alert(str);
return str;
}).get().join(", ");
alert() function works just fine and displays the proper value. But somehow, jquery's .get() function doesn't get the right sort of object and fails. What am I doing wrong?
If value is not a plain array, such code will work fine:
var value = { "aaa": "111", "bbb": "222", "ccc": "333" };
var blkstr = [];
$.each(value, function(idx2,val2) {
var str = idx2 + ":" + val2;
blkstr.push(str);
});
console.log(blkstr.join(", "));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
(output will appear in the dev console)
As Felix mentioned, each() is just iterating the array, nothing more.
Converting From Array to String is So Easy !
var A = ['Sunday','Monday','Tuesday','Wednesday','Thursday']
array = A + ""
That's it Now A is a string. :)
You can use .toString() to join an array with a comma.
var array = ['a', 'b', 'c'];
array.toString(); // result: a,b,c
Or, set the separator with array.join('; '); // result: a; b; c.
not sure if this is what you wanted but
var arr = ["A", "B", "C"];
var arrString = arr.join(", ");
This results in the following output:
A, B, C
Four methods to convert an array to a string.
Coercing to a string
var arr = ['a', 'b', 'c'] + []; // "a,b,c"
var arr = ['a', 'b', 'c'] + ''; // "a,b,c"
Calling .toString()
var arr = ['a', 'b', 'c'].toString(); // "a,b,c"
Explicitly joining using .join()
var arr = ['a', 'b', 'c'].join(); // "a,b,c" (Defaults to ',' seperator)
var arr = ['a', 'b', 'c'].join(','); // "a,b,c"
You can use other separators, for example, ', '
var arr = ['a', 'b', 'c'].join(', '); // "a, b, c"
Using JSON.stringify()
This is cleaner, as it quotes strings inside of the array and handles nested arrays properly.
var arr = JSON.stringify(['a', 'b', 'c']); // '["a","b","c"]'
jQuery.each is just looping over the array, it doesn't do anything with the return value∆. You are looking for jQuery.map (I also think that get() is unnecessary as you are not dealing with jQuery objects):
var blkstr = $.map(value, function(val,index) {
var str = index + ":" + val;
return str;
}).join(", ");
DEMO
But why use jQuery at all in this case? map only introduces an unnecessary function call per element.
var values = [];
for(var i = 0, l = value.length; i < l; i++) {
values.push(i + ':' + value[i]);
}
// or if you actually have an object:
for(var id in value) {
if(value.hasOwnProperty(id)) {
values.push(id + ':' + value[id]);
}
}
var blkstr = values.join(', ');
∆: It only uses the return value whether it should continue to loop over the elements or not. Returning a "falsy" value will stop the loop.
this's my function, convert object or array to json
function obj2json(_data){
str = '{ ';
first = true;
$.each(_data, function(i, v) {
if(first != true)
str += ",";
else first = false;
if ($.type(v)== 'object' )
str += "'" + i + "':" + obj2arr(v) ;
else if ($.type(v)== 'array')
str += "'" + i + "':" + obj2arr(v) ;
else{
str += "'" + i + "':'" + v + "'";
}
});
return str+= '}';
}
i just edit to v0.2 ^.^
function obj2json(_data){
str = (($.type(_data)== 'array')?'[ ': '{ ');
first = true;
$.each(_data, function(i, v) {
if(first != true)
str += ",";
else first = false;
if ($.type(v)== 'object' )
str += '"' + i + '":' + obj2json(v) ;
else if ($.type(v)== 'array')
str += '"' + i + '":' + obj2json(v) ;
else{
if($.type(_data)== 'array')
str += '"' + v + '"';
else
str += '"' + i + '":"' + v + '"';
}
});
return str+= (($.type(_data)== 'array')? ' ] ':' } ');;
}
var arr = new Array();
var blkstr = $.each([1, 2, 3], function(idx2,val2) {
arr.push(idx2 + ":" + val2);
return arr;
}).join(', ');
console.log(blkstr);
OR
var arr = new Array();
$.each([1, 2, 3], function(idx2,val2) {
arr.push(idx2 + ":" + val2);
});
console.log(arr.join(', '));
convert an array to a GET param string that can be appended to a url could be done as follows
function encodeGet(array){
return getParams = $.map(array , function(val,index) {
var str = index + "=" + escape(val);
return str;
}).join("&");
}
call this function as
var getStr = encodeGet({
search: $('input[name="search"]').val(),
location: $('input[name="location"]').val(),
dod: $('input[name="dod"]').val(),
type: $('input[name="type"]').val()
});
window.location = '/site/search?'+getStr;
which will forward the user to the /site/search? page with the get params outlined in the array given to encodeGet.
Here's an example using underscore functions.
var exampleArray = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
var finalArray = _.compact(_.pluck(exampleArray,"name")).join(",");
Final output would be "moe,larry,curly"
You shouldn't confuse arrays with lists.
This is a list: {...}. It has no length or other Array properties.
This is an array: [...]. You can use array functions, methods and so, like someone suggested here: someArray.toString();
someObj.toString(); will not work on any other object types, like lists.
I have a dynamically generated Array:
myArr = ["val0a", "val1a", "val2a"... "val600a"]
I am having problems appending a new array values to this array in a loop. My Array should look like this after the append:
myArr = ["val0a", "val1a val1b", "val2a val2b"... "val600a"]
Please note that the new array and the old one do not have the same length.
How can I do this? It have to be something simple but I can't figure it out.
You can write a function along the lines of this:
Array.prototype.appendStringToElementAtIndex = function(index, str) {
if(typeof this[index] === 'undefined' || typeof this[index] !== 'string') return false;
this[index] += ' ' + str;
};
myArr = ["val0a", "val1a", "val2a"];
myArr.appendStringToElementAtIndex(1, "val1b");
console.log(myArr.join(', ')); //val0a, val1a val1b, val2a
myArr.push(myArr[myArr.length - 1].split(" ").push("val42").join(" ")); // even
to append a value to an element of an array you can just do this:
myArr = ["val0a", "val1a", "val2a"... "val600a"];
indexToAppendTo = 2;
val2 = "val2b"
myArr[ indexToAppendTo ] += (" " + val2) ;
To concatenate to an element that's a string:
myArr[2] = myArr[2] += 'blah';
To reassign it:
myArr[2] = 'foo';