I have a 2D array that looks like:
var example = [['Version', 'Number'], [ 'V1.0', 1 ], [ 'V2.0', 2 ]];
I'd like to iterate through the array and take out 'V1.0' and 'V2.0' and store them in their own new array, and do the same for '1' and '2'. I need to break the data up for use with Chart.js
My loop looks like this:
var labels = [];
var data = [];
for (var i=0; i<example.length; i++) {
labels.push = (example[i][0]);
}
for (var j=0; j<example.length; j++) {
data.push = (example[0][j]);
}
I don't know how to properly get either element into their own array for use later.
You can use map to do this, and shift the result in order to remove the first occurence.
var example = [
['Version', 'Number'],
['V1.0', 1],
['V2.0', 2]
];
var result = example.map(e => e[0])
console.log(result);
From what I saw into your example the first pair of elements are the keys for your data, into your example will include them into your final arrays.
This example will generate to a dictionary with the keys Number and Version containing the corresponding values from your array.
var example = [['Version', 'Number'], [ 'V1.0', 1 ], [ 'V2.0', 2 ]];
function extract(items) {
var keys = {},
version = items[0][0],
number = items[0][1];
keys[version] = [];
keys[number] = [];
return items.slice(1).reduce(function(acc, item) {
acc[version].push(item[0]);
acc[number].push(item[1]);
return acc;
}, keys);
}
var result = extract(example);
console.log(result);
From this point you can do something like:
var labels = result.Version;
var data = result.Number;
This looks like what you are trying to achieve:
for(var i=0; i<example.length; i++){
labels.push(example[i][0])
data.push(example[i][1])
}
Related
I am new to JavaScript and want to process the following array -
var a = [
"John-100",
"Mark-120",
"John-50",
"Mark-130"
]
into the following format -
a = {
"John": [100, 50],
"Mark": [120, 130]
}
But have been unable to do so. Any help will be very much appreciated.
Edit - Any other format ideas where the marks of a particular student can be grouped together are also welcome.
Here is one way to achieve what you described:
var a=[
"John-100",
"Mark-120",
"John-50",
"Mark-130"
]
function convertToSpecialObject(input) {
//setup the output as an empty object
const output = {};
// iterate through input array one element at a time
input.forEach(e => {
// split the current element by dividing it into part[0] before the dash
// and part[1] after the dash sign
const parts = e.split(/-/);
// now check the output object if it already contains a key for the part before the dash
if(!output[parts[0]]) {
// in this case, we don't have a key for it previously
// so lets set it up as a key with an empty array
output[parts[0]] = [];
}
// we must have already created a key or there is a key in existence
// so let's just push the part after the dash to the current key
output[parts[0]].push(Number(parts[1]));
});
// work done
return output;
}
const b = convertToSpecialObject(a);
console.log(b);
you can achieve this by using reduce and split method
var a=[
"John-100",
"Mark-120",
"John-50",
"Mark-130"
]
const b = a.reduce((acc, val) => {
const _split = val.split('-');
const name = _split[0]
if(acc && acc[name]) {
acc[name].push(+_split[1])
} else {
acc[name] = [+_split[1]]
}
return acc;
}, {});
console.log(b)
You can achieve it in a very simple way by just using a Array.forEach() method along with the String.split().
Live Demo :
var a = [
"John-100",
"Mark-120",
"John-50",
"Mark-130"
];
const obj = {};
a.forEach(element => {
if (!obj[element.split('-')[0]]) {
obj[element.split('-')[0]] = [];
}
obj[element.split('-')[0]].push(element.split('-')[1])
});
console.log(obj);
With Simple Approach
const input = [
"John-100",
"Mark-120",
"John-50",
"Mark-130"
];
const getCustomObject = (arr) => {
const obj = {};
for (let i = 0; i < arr.length; i++) {
const split = arr[i].split('-'); //spliting with '-'
if (obj[split[0]]) {
//push to existing array
obj[split[0]].push(split[1]);
} else {
obj[split[0]] = []; //initilize array if no member
obj[split[0]].push(split[1]);
}
};
return obj;
}
console.log(getCustomObject(input));
Now numbers are not numerical values, It can be achieved with parseInt or parseFloat
As I suggested, string split, and array reduce - add in an array map and it's a single line of code
let a=["John-100","Mark-120","John-50","Mark-130"];
a=a.map(v=>v.split('-')).reduce((r,[n,m])=>({...r,[n]:[...r[n]||[],+m]}),{});
console.log(JSON.stringify(a));
The only answer with the correct result ... an array of NUMBERS
I have an array
var arr= [
["PROPRI","PORVEC"],
["AJATRN","PROPRI"],
["BASMON","CALVI"],
["GHICIA","FOLELI"],
["FOLELI","BASMON"],
["PORVEC","GHICIA"]
] ;
And I'm trying to sort the array by making the second element equal to the first element of the next, like below:
arr = [
["AJATRN","PROPRI"],
["PROPRI","PORVEC"],
["PORVEC","GHICIA"],
["GHICIA","FOLELI"],
["FOLELI","BASMON"],
["BASMON","CALVI"]
]
The context is : these are somes sites with coordinates, I want to identify the order passed,
For exemple, I have [A,B] [C,D] [B,C] then I know the path is A B C D
I finally have one solution
var rs =[];
rs[0]=arr[0];
var hasAdded=false;
for (var i = 1; i < arr.length; i++) {
hasAdded=false;
console.log("i",i);
for (var j = 0, len=rs.length; j < len; j++) {
console.log("j",j);
console.log("len",len);
if(arr[i][1]===rs[j][0]){
rs.splice(j,0,arr[i]);
hasAdded=true;
console.log("hasAdded",hasAdded);
}
if(arr[i][0]===rs[j][1]){
rs.splice(j+1,0,arr[i]);
hasAdded=true;
console.log("hasAdded",hasAdded);
}
}
if(hasAdded===false) {
arr.push(arr[i]);
console.log("ARR length",arr.length);
}
}
But it's not perfect, when it's a circle like [A,B] [B,C] [C,D] [D,A]
I can't get the except answer
So I really hope this is what you like to achieve so have a look at this simple js code:
var vector = [
["PROPRI,PORVEC"],
["AJATRN,PROPRI"],
["BASMON,CALVI"],
["GHICIA,FOLELI"],
["FOLELI,BASMON"],
["PORVEC,GHICIA"]
]
function sort(vector) {
var result = []
for (var i = 1; i < vector.length; i++) result.push(vector[i])
result.push(vector[0])
return (result)
}
var res = sort(vector)
console.log(res)
Note: Of course this result could be easily achieved using map but because of your question I'm quite sure this will just confuse you. So have a look at the code done with a for loop :)
You can create an object lookup based on the first value of your array. Using this lookup, you can get the first key and then start adding value to your result. Once you add a value in the array, remove the value corresponding to that key, if the key has no element in its array delete its key. Continue this process as long as you have keys in your object lookup.
var vector = [["PROPRI", "PORVEC"],["AJATRN", "PROPRI"],["BASMON", "CALVI"],["GHICIA", "FOLELI"],["FOLELI", "BASMON"],["PORVEC", "GHICIA"]],
lookup = vector.reduce((r,a) => {
r[a[0]] = r[a[0]] || [];
r[a[0]].push(a);
return r;
}, {});
var current = Object.keys(lookup).sort()[0];
var sorted = [];
while(Object.keys(lookup).length > 0) {
if(lookup[current] && lookup[current].length) {
var first = lookup[current].shift();
sorted.push(first);
current = first[1];
} else {
delete lookup[current];
current = Object.keys(lookup).sort()[0];
}
}
console.log(sorted);
What's the best way to convert this array of comma separated values
[ 'com--test,LFutx9mQbTTyRo4A9Re5ksjdnfsI4cKN4q2,on',
'com--fxtrimester,SEzlksdfMpW3FxkSbzL7eo5MmqkPczCl2,on',
'com--fxtrimester,LFutx9mQbTTyRoldksfns4A9Re5I4cKN4q2,on' ]
Into three arrays?
[ 'com--test', [ LFutx9mQbTTyRo4A9Re5Ilsdf4cKN4q2', ['on',
'com--fxtrimester', SEzMpW3FxkSbzL7eo5MmlkdfqkPczCl2', 'on',
'com--fxtrimester' ] LFutksdfx9mQbTTyRo4A9Re5I4cKN4q2 ] 'on']
I was trying something like:
var indexToSplit = unique.indexOf(',');
var status = unique.slice(3, indexToSplit - 1);
var use = unique.slice(2, indexToSplit - 2);
var pros = unique.slice(0, indexToSplit - 3);
console.log(pros);
But I figured that is wrong ... any help is appreciated!
You will have to loop over array and use string.split to get seperate parts.
Once you have seperate parts, you can push them to necessary array;
var d = [ 'com--test,LFutx9mQbTTyRo4A9Re5ksjdnfsI4cKN4q2,on',
'com--fxtrimester,SEzlksdfMpW3FxkSbzL7eo5MmqkPczCl2,on',
'com--fxtrimester,LFutx9mQbTTyRoldksfns4A9Re5I4cKN4q2,on'];
var result = [[],[],[]];
var len = 3;
d.forEach(function(str, i){
var _tmp = str.split(',');
for (var i = 0; i<len; i++){
result[i].push(_tmp[i])
}
})
console.log(result)
A little generic way.
Loop over data and split each string using comma(,)
Loop over split values and check if necessary array exists.
If not, initialise array, but you cannot do p[i] = [] as this will push to first value. You will have to also initialise all previous values. For this, you can use new Array(length). By default, if length is greater than 0, all indexes will be initialise to undefined.
Now push to necessary array. Position will be maintained.
var d = ['com--test,LFutx9mQbTTyRo4A9Re5ksjdnfsI4cKN4q2,on',
'com--fxtrimester,SEzlksdfMpW3FxkSbzL7eo5MmqkPczCl2,on',
'com--fxtrimester,LFutx9mQbTTyRoldksfns4A9Re5I4cKN4q2,on,test'
];
var result = d.reduce(function(p, c, index) {
var _tmp = c.split(',');
for (var i = 0; i < _tmp.length; i++) {
// Check if position not defined.
if (p[i] === undefined)
// Initialize array and add default (undefined) to all elements before current element
p[i] = new Array(index);
p[i].push(_tmp[i])
}
return p;
}, [])
console.log(result)
With map this becomes:
for positions X out of 0, 1 and 2:
convert each item in the list into an array, and choose the Xth item
var start = [ 'com--test,LFutx9mQbTTyRo4A9Re5ksjdnfsI4cKN4q2,on',
'com--fxtrimester,SEzlksdfMpW3FxkSbzL7eo5MmqkPczCl2,on',
'com--fxtrimester,LFutx9mQbTTyRoldksfns4A9Re5I4cKN4q2,on' ]
var out = [0,1,2].map(i =>
start.map(x => x.split(',')[i]) )
console.log(out)
Since your question does not ask for a more general case, i am safely assuming it for 3 array. We can use forEach function on array below code can be one amongst the possible solutions
var arr1 = [];
var arr2 = [];
var arr3 = [];
var x = ['com--test,LFutx9mQbTTyRo4A9Re5ksjdnfsI4cKN4q2,on', 'com--fxtrimester,SEzlksdfMpW3FxkSbzL7eo5MmqkPczCl2,on', 'com--fxtrimester,LFutx9mQbTTyRoldksfns4A9Re5I4cKN4q2,on']
x.forEach(function(data) {
var dataArray = data.split(',');
arr1.push(dataArray[0]);
arr2.push(dataArray[1]);
arr3.push(dataArray[2]);
});
console.log(arr1)
console.log(arr2)
console.log(arr3)
I have a string that looks like this:
str = {1|2|3|4|5}{a|b|c|d|e}
I want to split it into multiple arrays. One containing all the first elements in each {}, one containing the second element, etc. Like this:
arr_0 = [1,a]
arr_1 = [2,b]
arr_2 = [3,c]
.....
The best I can come up with is:
var str_array = str.split(/}{/);
for(var i = 0; i < str_array.length; i++){
var str_row = str_array[i];
var str_row_array = str_row.split('|');
arr_0.push(str_row_array[0]);
arr_1.push(str_row_array[1]);
arr_2.push(str_row_array[2]);
arr_3.push(str_row_array[3]);
arr_4.push(str_row_array[4]);
}
Is there a better way to accomplish this?
Try the following:
var zip = function(xs, ys) {
var out = []
for (var i = 0; i < xs.length; i++) {
out[i] = [xs[i], ys[i]]
}
return out
}
var res = str
.split(/\{|\}/) // ['', '1|2|3|4|5', '', 'a|b|c|d|e', '']
.filter(Boolean) // ['1|2|3|4|5', 'a|b|c|d|e']
.map(function(x){return x.split('|')}) // [['1','2','3','4','5'], ['a','b','c','d','e']]
.reduce(zip)
/*^
[['1','a'],
['2','b'],
['3','c'],
['4','d'],
['5','e']]
*/
Solution
var str = '{1|2|3|4|5}{a|b|c|d|e}'.match(/[^{}]+/g).map(function(a) {
return a.match(/[^|]+/g);
}),
i,
result = {};
for (i = 0; i < str[0].length; i += 1) {
result["arr_" + i] = [+str[0][i], str[1][i]];
}
How it works
The first part, takes the string, and splits it into the two halves. The map will return an array after splitting them after the |. So str is left equal to:
[
[1,2,3,4,5],
['a', 'b', 'c', 'd', 'e']
]
The for loop will iterate over the [1,2,3,4,5] array and make the array with the appropriate values. The array's are stored in a object. The object we are using is called result. If you don't wish for it to be kept in result, read Other
Other
Because you can't make variable names from another variable, feel free to change result to window or maybe even this (I don't know if that'll work) You can also make this an array
Alternate
var str = '{1|2|3|4|5}{a|b|c|d|e}'.match(/[^{}]+/g).map(function(a) { return a.match(/[^|]+/g); }),
result = [];
for (var i = 0; i < str[0].length; i += 1) {
result[i] = [+str[0][i], str[1][i]];
}
This is very similar except will generate an Array containing arrays like the other answers,
How can I convert something like initialArray array of JSON objects into finalObject map?
var initialArray = [
{ id:'id1', name:'name1' },
{ id:'id2', name:'name2' },
{ id:'id3', name:'name3' },
{ id:'id4', name:'name4' }
];
var finalObject = {
'id1':'name1',
'id2':'name2',
'id3':'name3',
'id4':'name4'
}
Things to consider:
IDs are strings.
I tried for in loop - couldn't make it to work - http://jsfiddle.net/5af9R/23/
Any ideas?
You need to operate on the objects in your array, not strings containing their indexes in the array.
You should also use a regular for loop to iterate over an array.
Your JSFiddle, fixed:
var x = [ {id:'1', img:'img1'}, {id:'2', img:'img2'}, {id:'3', img:'img3'} ];
var resp = {};
for( var i = 0 ; i < x.length ; i++ ){
var obj = x[i];
resp[obj.id] = obj.img;
}
document.write( JSON.stringify(resp, undefined, 2) );
DEMO
You can loop over the array, and for each object, add a new property to finalObject whose property name is the id, and whose value is the name.
var finalObject = {};
for (var i = 0, max = initialArray.length; i < max; i++)
finalObject[initialArray[i].id] = initialArray[i].name;
resp[key.id] = key.img;
You correctly call it key. But you need a value;
resp[x[key].id] = x[key].img;
var finalObject = initialArray.reduce(function(ret, obj){
ret[obj.id] = obj.name;
return ret;
}, {});
This solution is specific to the property names for the specific question, but Array.prototype.reduce is a function I use all the time for any sort of array iteration that requires a non-array result.
You're not using For In correctly jsFiddle
var x = [ {id:'1', img:'img1'}, {id:'2', img:'img2'}, {id:'3', img:'img3'} ];
var resp = {};
for( var key in x ){
resp['id' + x[key].id] = x[key].img;
}
document.write( JSON.stringify(resp, undefined, 2) );
for (var i=0; i<x.length; i++) {
var id = 'id' + x[i].id;
var img = x[i].img;
resp[id] = img;
}
if i have understood correctly you can do something like
var x =' [ {"id":"1", "img":"img1"}, {"id":"2", "img":"img2"}, {"id":"3", "img":"img3"}]';
var resp = {};
var json = $.parseJSON(x);
$(json).each(function(i,v){
resp[v.id]=v.img;
});
console.log( resp);
DEMO
you talked about json but in the fiddle you provided there was no json even jquery was not added as a resource so i made some assumptions
Today I was on the same question and I didn't find an answer here, except the answer of #adam-rackis.
The way I found is :
var initialArray = [
{ id:'id1', name:'name1' },
{ id:'id2', name:'name2' },
{ id:'id3', name:'name3' },
{ id:'id4', name:'name4' }
],
finalObject = {};
$.each(initialArray, function(k,v) {
finalObject[v.name] = v.value;
});