I have an array
var arr = ["2:6", "2:3", "1:1", "1:2", "3:1"];
(This is javascript); I don't know how to convert this array into output:
["2:6,3", "1:1,2", "3:1"];
May be you can help me?
I have an array
var arr = ["2:6", "2:3", "1:1", "1:2", "3:1"];
(This is javascript); I don't know how to convert this array into output:
["2:6,3", "1:1,2", "3:1"];
May be you can help me?
It looks like you want to group together the elements of the list who have the same initial digit. This code will give you the associative array {"1":"1,2","2":"6,3","3§:"1"}
as an output:
var arr = ["2:6", "2:3", "1:1", "1:2", "3:1"];
var hist = {};
arr.map( function (a) { b=a.split(":");c=b[0]; if (c in hist) hist[c]=hist[c].concat(","+b[1]); else hist[c] = b[1]; } );
alert(JSON.stringify(hist));
See also JavaScript Group By Array
var interm = {}, output = [], regx = /(\d+):(\d+)/;
arr.forEach(function(x) {var y = regx.exec(x); if (y[1] in interm) interm[y[1]].push(y[2]); else interm[y[1]] = [y[2]]});
Object.keys(interm).map(function(x) { output.push(x + ":" + interm[x].join(',')) });
console.log(output);
[ '1:1,2', '2:6,3', '3:1' ]
That's far from the most efficient conversion in terms of speed as it uses regex and forEach
, but it's fairly concise and you didn't mention that you needed anything particularly quick.
Please see this LINK..
or apply below code...
HTML Code...
<input type='button' id='s' value='test' onclick="test()"/>
JQuery code...
function test() {
var arr = ["2:6", "2:3", "1:1", "1:2", "3:1"];
var resultStr = "";
for (i = 0; i < arr.length; i++) {
if (i <= arr.length - 2) {
var a = arr[i + 1].split(":");
if (a.length > 0) {
resultStr += arr[i] + ',' + a[1] + ' | ';
}
} else {
var str = arr[i];
resultStr += arr[i];
}
i++;
}
alert(resultStr);
}
Your output looks a lot like a map. I would write it as:
{
2 : [ 6, 3 ],
1 : [ 1, 2 ],
3 : [ 1 ]
}
To get that map, i would iterate over the array, extracting the key and value and then adding the value to the correct array, making sure to create it if it hasn't been created already.
var arr = ["2:6", "2:3", "1:1", "1:2", "3:1"];
var map = {};
arr.forEach(function(item){
var split = item.split(':');
if (!map[split[0]]) map[split[0]] = [split[1]];
else map[split[0]].push(split[1]);
});
Obviously from my map you can get your desired array quite easily:
var result = [];
for (var key in map) {
if (map.hasOwnProperty(key)) // best practice
result.push(key+':'+map[key]);
}
console.log(result); // ["1:1,2", "2:6,3", "3:1"]
One note: it doesn't have the items in the same order you do, but that can easily be fixed by iterating over the original array to get the keys instead of using for..in:
var result = [];
arr.forEach(function(item){
var key = item.split(':')[0];
if (map[key]) {
result.push(key+':'+map[key]);
delete map[key]; // destroys the map!
}
});
console.log(result); // ["2:6,3", "1:1,2", "3:1"]
Solution 2 (no intermediate map):
This solution has O(n^2) complexity:
var arr = ["2:6", "2:3", "1:1", "1:2", "3:1"];
var result = [];
for (var i=0; i<arr.length; i++) {
if (!arr[i]) continue;
var key = arr[i].split(':')[0];
var values = [];
for (var j=i; j<arr.length; j++) {
var split = arr[j].split(':');
if (split[0] === key) {
values.push(split[1]);
arr[j] = undefined; // destroys the original array
}
}
result.push(key + ':' + values);
}
console.log(result); // ["2:6,3", "1:1,2", "3:1"]
Here is an working example on JSFiddle
And the sample code below,
var arr = ["2:6", "2:3", "1:1", "1:2", "3:1"];
var tdarray = {};
var newarray = [];
for(var i=0;i<arr.length;i++){
var data = arr[i].split(":");
var found = false;
for(var key in tdarray){
if(data[0]==key){
found = true;
break;
}
}
var list=[];
if(found){
list = tdarray[data[0]];
}
list.push(data[1]);
tdarray[data[0]] = list;
}
for(key in tdarray){
var data = key + ":" + tdarray[key].join();
newarray.push(data);
}
console.log(newarray);
And another possible solution...
var arr = ["2:6", "2:3", "1:1", "1:2", "3:1"], alreadyUsedNumbers = [];
for (var i=0; i < arr.length; i++) {
var key = arr[i].split(":")[0], value = arr[i].split(":")[1];
if (alreadyUsedNumbers.indexOf(key) >= 0) {
for (var j=0; j < i; j++) {
if (arr[j].indexOf(key) == 0) {
arr[j] += ","+value;
arr.splice(i, 1)
i--;
break;
}
}
} else {
alreadyUsedNumbers.push(key);
}
}
console.log(arr);
... enjoy.
var arr = ["2:6", "2:3", "1:1", "1:2", "3:1", "4:6", "3:4"];
var output = new Array();
var outputString = "[";
for(var i=0; i<arr.length; i++)
{
var index = arr[i].indexOf(":");
var firstNr = arr[i].substring(0,index);
var secondNr = arr[i].substring(index+1,arr[i].length);
var outputPart = firstNr + ":" + secondNr;
var j = i+1;
while (j<arr.length)
{
var index2 = arr[j].indexOf(":");
var firstNr2 = arr[j].substring(0,index2);
var secondNr2 = arr[j].substring(index2+1,arr[j].length);
if (firstNr == firstNr2)
{
outputPart += "," + secondNr2;
arr.splice(j,1);
}
else
j++;
}
output.push(outputPart);
}
for(var k=0; k<output.length; k++)
outputString += "'" + output[k] + "' ";
outputString += "]";
alert(outputString);
Demo here: http://jsfiddle.net/er144/QYca2/