I have an array (call it array[]), with elements of the following format separated by a comma:
array[0] = abc, def, 123, ghi
How can I pass this into another multi-dimensional array (lets say arrayTwo[]) such that arrayTwo is as follows:
arrayTwo[0][0] = "abc"
arrayTwo[0][1] = "def"
arrayTwo[0][2] = "123"
arrayTwo[0][3] = "ghi"
I am really unsure about the comma as a delimiter portion (use split()?). I believe the looping part should not be too difficult for me to handle. Thanks for any help!
You can split the items by ,\s* regex which is comma followed by zero or more spaces. This will create an array. Then just insert that array into the appropriate element of arrayTwo.
arrayTwo = array.map(function (item) {
return item.split(/,\s*/)
});
Unrolled slightly it would look like:
arrayTwo = [];
for (var x = 0; x < array.length; x++) {
var item = array[x].split(/,\s*/);
arrayTwo[x] = [];
for (var i = 0; i < item.length; i++) {
arrayTwo[x][i] = item[i];
}
}
Related
I have an array consisting of a list of words, and a wordcount and ID for each word. Sort of like:
var array = [[word1, word2, word3],[3,5,7],[id1,id2,id3]]
Now I want to create an object for each word with the word as the name and the count and ID as values. So it would look like this:
var word1 = {count: 3, id: 'id1'}
How do I achieve this?
I tried doing it using a for-loop as shown below, but it doesn't work. How could I set the name of each object from the values in the array?
for (var y=0; y < array[0].length; y++) {
var array[0][y] = {count: array[1][y], id: array[2][y]};
}
Instead of having individual objects you could add the words in one dict object like this:
var words = {};
for (var y=0; y < array[0].length; y++) {
words[array[0][y]] = {count: array[1][y], id: array[2][y]};
}
And, you can access word1 as following:
words['word1'] // {count: 1, id: id1}
// if the word1 doesn't contain spaces, you could also use
words.word1 // {count: 1, id: id1}
If you know that the array [0] are the ordered keys, and array[1] are the count and array[2] are the ids then:
var array = [[word1, word2, word3],[3,5,7],[id1,id2,id3]];
var orderedKeysArray = array[0];
var orderedCountArray = array[1];
var orderedIdArray = array[2];
//maybe add some code here to check the arrays are the same length?
var object = {};
//add the keys to the object
for(var i = 0; i < orderedKeysArray.length; i++) {
object[orderedKeys[i]] = {
count: orderedCountArray[i],
id: orderedIdArray[i]
};
}
Then you can refer to the object for the vars like so:
object.word1;
object.word2;
object.word3;
Loadash
var array = [['word1', 'word2', 'word3'],[3,5,7],['id1','id2','id3']]
var output = _.reduce(array[0], function (output, word, index) {
output[word] = {count:array[1][index],id:array[2][index]};
return output;
},{});
Folks,
I have looked at underscore.string and string.js modules and still can't find a good way to do the following:
Suppose I have a query string string:
"!dogs,cats,horses!cows!fish"
I would like to pass it to a function that looks for all words that start with !, and get back an Array:
['dogs','cows','fish']
Similarly, the same function should return an array of words that start with ,:
['cats','horses]
Thanks!!!
You can use RegEx to easily match the split characters.
var string = "!dogs,cats,horses!cows!fish";
var splitString = string.split(/!|,/);
// ["dogs", "cats", "horses", "cows", "fish"]
The only issue with that is that it will possibly add an empty string at the beginning of the array if you start it with !. You could fix that with a function:
splitString.forEach(function(item){
if(item === ""){
splitString.splice(splitString.indexOf(item), 1)
}
});
EDIT:
In response to your clarificaiton, here is a function that does as you ask. It currently returns an object with the values commas and exclaim, each with an array of the corresponding elements.
JSBin showing it working.
function splitString(str){
var exclaimValues = [];
var expandedValues = [];
var commaValues = [];
var needsUnshift = false;
//First split the comma delimited values
var stringFragments = str.split(',');
//Iterate through them and see if they contain !
for(var i = 0; i < stringFragments.length; i++){
var stringValue = stringFragments[i];
// if the value contains an !, its an exclaimValue
if (stringValue.indexOf('!') !== -1){
exclaimValues.push(stringValue);
}
// otherwise, it's a comma value
else {
commaValues.push(stringValue);
}
}
// iterate through each exclaim value
for(var i = 0; i < exclaimValues.length; i++){
var exclaimValue = exclaimValues[i];
var expandedExclaimValues = exclaimValue.split('!');
//we know that if it doesn't start with !, the
// the first value is actually a comma value. So move it
if(exclaimValue.indexOf('!') !== 0) commaValues.unshift(expandedExclaimValues.shift());
for(var j = 0; j < expandedExclaimValues.length; j++){
var expandedExclaimValue = expandedExclaimValues[j];
//If it's not a blank entry, push it to our results list.
if(expandedExclaimValue !== "") expandedValues.push(expandedExclaimValue);
}
}
return {comma: commaValues, exclaim: expandedValues};
}
So if we do:
var str = "!dogs,cats,horses!cows!fish,comma!exclaim,comma2,comma3!exclaim2";
var results = splitString(str)
results would be:
{
comma: ["comma3", "comma", "horses", "cats", "comma2"],
exclaim: ["dogs", "cows", "fish", "exclaim", "exclaim2"]
}
Help needed.
I have string like ["wt=WLw","V5=9jCs","7W=71X","rZ=HRP9"] (unlimited number of pairs)
I need to make an array with pair like wT (as index) and WLw as value, for the whole string (or simpler wT as index0, WLw as index 1 and so on)
I'm trying to do it in JavaScript but I just cant figure out how to accomplish this task.
Much much appreciate your help!!
You cannot have a string as an index in an array, what you want is an object.
All you need to do is loop over your array, split each value into 2 items (key and value) then add them to an object.
Example:
// output is an object
var output = {};
var source = ["wt=WLw","V5=9jCs","7W=71X","rZ=HRP9"];
for (var index = 0; index < source.length; index++) {
var kvpair = source[index].split("=");
output[kvpair[0]] = kvpair[1];
}
If you wanted an array of arrays, then its much the same process, just pushing each pair to the output object
// output is a multidimensional array
var output = [];
var source = ["wt=WLw","V5=9jCs","7W=71X","rZ=HRP9"];
for (var index = 0; index < source.length; index++) {
output.push(source[index].split("="));
}
Update If your source is actually a string and not an array then you will have to do a little more splitting to get it to work
var output = {};
var sourceText = "[\"wt=WLw\",\"V5=9jCs\",\"7W=71X\",\"rZ=HRP9\"]";
// i have escaped the quotes in the above line purely to make my example work!
var source = sourceText.replace(/[\[\]]/g,"").split(",");
for (var index = 0; index < source.length; index++) {
var kvpair = source[index].split("=");
output[kvpair[0]] = kvpair[1];
}
Update 2
If your desired output is an array of arrays instead of an object containing key-value pairs then you will need to do something like #limelights answer.
Object with Key-Value pairs: var myObject = { "key1": "value1", "key2": "value2" };
with the above code you can access "value1" like this myObject["key1"] or myObject.key1
Array of Arrays: var myArray = [ [ "key1", "value1"] ,[ "key2", "value2" ] ];
with this code, you cannot access the data by "key" (without looping through the whole lot to find it first). in this form both "key1" and "value1" are actually values.
to get "value1" you would do myArray[0][1] or you could use an intermediary array to access the pair:
var pair = myArray[0];
> pair == ["key1", "value1"]
> pair[0] == "key1"
> pair[1] == "value1"
You can use a for each loop on both types of result
// array of arrays
var data = [ [ "hello", "world"], ["goodbye", "world"]];
data.forEach(function(item) {
console.log(item[0]+" "+item[1]);
});
> Hello World
> Goodbye World
// object (this one might not work very well though)
var data = { "hello": "world", "goodbye": "world" };
Object.keys(data).forEach(function(key) {
console.log(key+" "+data[key]);
});
> Hello World
> Goodbye World
The normal for loop would do perfectly here!
var list = ["wt=WLw","V5=9jCs","7W=71X","rZ=HRP9"];
var pairs = [];
for(var i = 0; i < list.length; i++){
pairs.push(list[i].split('='));
}
This would give you an array of pairs, which I assume you want.
Otherwise just get rid of the outer Array and do list[i].split('=');
If you want it put into an object ie. not an Array
var pairObject = {};
for(var i = 0; i < list.length; i++){
var pair = list[i].split('=');
pairObject[pair[0]] = pair[1];
}
If I have the following string:
mickey mouse WITH friend:goofy WITH pet:pluto
What is the best way in javascript to take that string and extract out all the "key:value" pairs into some object variable? The colon is the separator. Though I may or may not be able to guarantee the WITH will be there.
var array = str.match(/\w+\:\w+/g);
Then split each item in array using ":", to get the key value pairs.
Here is the code:
function getObject(str) {
var ar = str.match(/\w+\:\w+/g);
var outObj = {};
for (var i=0; i < ar.length; i++) {
var item = ar[i];
var s = item.split(":");
outObj[s[0]] = s[1];
}
return outObj;
}
myString.split(/\s+/).reduce(function(map, str) {
var parts = str.split(":");
if (parts.length > 1)
map[parts.shift()] = parts.join(":");
return map;
}, {});
Maybe something like
"mickey WITH friend:goofy WITH pet:pluto".split(":")
it will return the array, then Looping over the array.
The string pattern has to be consistent in one or the other way atleast.
Use split function of javascript and split by the word that occurs in common(our say space Atleast)
Then you need to split each of those by using : as key, and get the required values into an object.
Hope that's what you were long for.
You can do it this way for example:
var myString = "mickey WITH friend:goofy WITH pet:pluto";
function someName(str, separator) {
var arr = str.split(" "),
arr2 = [],
obj = {};
for(var i = 0, ilen = arr.length; i < ilen; i++) {
if ( arr[i].indexOf(separator) !== -1 ) {
arr2 = arr[i].split(separator);
obj[arr2[0]] = arr2[1];
}
}
return obj;
}
var x = someName(myString, ":");
console.log(x);
My array contains the values with comma as separator, like
array={raju,rani,raghu,siva,stephen,varam}.
But i want to convert into the below format like
array = {raju:rani raghu:siva atephen:varam}.
please give some logic to implement this one.
If you're starting with a string, you can split it upon comma:
var myString = 'raju,rani,raghu,siva,stephen,varam';
var array = myString.split(',');
Given that, you can do the following:
var array = [ 'raju', 'rani', 'raghu', 'siva', 'stephen', 'varam' ];
var result = {};
for(var i = 0; i < array.length; i+= 2) {
result[array[i]] = array[i+1];
}
... which gives the answer you've requested.
Keep in mind that if the array is not evenly divisible by 2, the value of the last item will be undefined.
This is how to convert array to key-value pair of objects (odd-index is key, even-index is value in the resulting key-value pairs)
var array = ['raju', 'rani', 'raghu','siva','stephen','varam'],
pairs = {};
for (var i = 0; i < array.length; i += 2) {
pairs [array[i]] = array[i + 1];
}