Split array as per values in it - javascript

I have array like this
var aaa = [
[value1,value2],[0,0]],
[[value3,value4],[0,1]],
[[value5,value6],[1,0]],
[[value7,value8],[0,2]],
[[value9,value10],[1,1]],
[value11,value12],[2,0]]
];
I want to split this array into multiple arrays as per values [0,1], [0,2], etc.
I.e.
array1 = [[value1,value2],[value3,value4],[value7,value8]];
array2 = [[value5,value6],[value9,value10]];
array3 = [[value11,value12]];
How can I do this ?

Use this:
var aaa = [
[['value1','value2'],[0,1]],
[['value3','value4'],[0,2]],
[['value5','value6'],[1,0]],
[['value7','value8'],[0,3]],
[['value9','value10'],[1,1]],
[['value11','value12'],[2,0]]];
var result = {};
for (var i = 0; i < aaa.length; i += 1) {
if (!result[aaa[i][1][0]]) {
result[aaa[i][1][0]] = [];
}
result[aaa[i][1][0]].push(aaa[i][0]);
}
After that:
result[0]; //[[value1,value2],[value3,value4],[value7,value8]];
result[1]; //[[value5,value6],[value9,value10]];
result[2]; //[[value5,value6],[value9,value10]];

Supposing this :
[['value1','value2'],[0,1]]
In this example :
0 tell in which array the value must be stored.
1 tell in which cell of this array it must be stored.
This code would do the work :
var aaa = [
[['value1','value2'],[0,1]],
[['value3','value4'],[0,2]],
[['value5','value6'],[1,0]],
[['value7','value8'],[0,3]],
[['value9','value10'],[1,1]],
[['value11','value12'],[2,0]]
];
var arr_result = new Array();
for (var k in aaa) {
if (arr_result[aaa[k][1][0]] == undefined) {
arr_result[aaa[k][1][0]] = new Array();
}
arr_result[aaa[k][1][0]][aaa[k][1][1]] = aaa[k][0];
}
Warning : this could let empty cells, just as in this example, there is no [0,0] cell.

Related

Javascript: Adding final element to array after for loop completes

Explanation of Desired Results
My source is over 30,000 lines of very structured text with incrementing front numbers followed by incrementing back numbers and separated by a colon. Stripping out the non-essentials, I am left with the following sourceArray, truncated for convenience :)
sourceArray = ["001:001", "001:002", "001:003",
"002:001", "002:002",
"003:001", "003:002"];
I am trying to count how many back numbers for each front number and push that to an array. In pseudocode, my final results should look like this:
myArray[totalNumberOf_001_Items, totalNumberOf_002_Items, totalNumberOf_003_Items]
Which in my simple example should give me a final value of:
[3, 2, 2]
Problem and Question
My for loop ends at the end of my data and I am therefore one element short in my array.
How do I make an "extra pass" through the loop or is there another way to get the final element pushed to my array?
var sourceArray = ["001:001", "001:002", "001:003",
"002:001", "002:002",
"003:001", "003:002"
];
var myArray = [];
var frontCounter = 1;
var backCounter = 1;
for (var i = 0; i < sourceArray.length; i++) {
var text = sourceArray[i];
var front = text.substr(0, 3);
front = Number(front);
var back = text.substr(4, 3);
back = Number(back);
if (front == frontCounter) {
backCounter++;
} else {
myArray.push(backCounter - 1);
backCounter = 2;
frontCounter++;
}
}
console.log(myArray); // result [3, 2]
You could use an object like below to keep track of how many times the the piece of text appear, the text would be the keys and as value the number of times they appear. From that you can build you array
var sourceArray = ["001:001", "001:002", "001:003",
"002:001", "002:002",
"003:001", "003:002"];
var frontEncounters = {};
function updateFrontEncounters(frontEncounters, front){
var keys = Object.keys(frontEncounters);
if(keys.indexOf(front) == -1)
{
frontEncounters[front] = 1;
}
else
{
frontEncounters[front] += 1;
}
}
for(var item in sourceArray){
var text = sourceArray[item];
var front = text.substr(0, 3);
var back = text.substr(4, 3);
updateFrontEncounters(frontEncounters, front);
}
var keys = Object.keys(frontEncounters);
var myArr = [];
for(var key in keys)
{
myArr.push(frontEncounters[keys[key]])
}
console.log(myArr);
Use an object to store the "front" numbers along with their count.
for (var i = 0; i < sourceArray.length; i++) {
var num = sourceArray[i].slice(0,3);
counts[num] = counts[num] ? counts[num]+1 : 1;
}
Once done, you can very easily convert that to an array:
var result = Object.keys(counts).map(function (key) {
return counts[key];
});
With ES-2017, it is even easier:
var result = Object.values(counts)
Working Snippet:
var sourceArray = ["001:001", "001:002", "001:003",
"002:001", "002:002",
"003:001", "003:002"];
var counts = {};
for (var i = 0; i < sourceArray.length; i++) {
var num = sourceArray[i].slice(0,3);
counts[num] = counts[num] ? counts[num]+1 : 1;
}
console.log(counts);
var result = Object.keys(counts).map(function (key) {
return counts[key];
});
console.log(result);
// ES-2017
//console.log(Object.values(counts));
Here's an alternative that you can use so that you don't have to go through the entire source of lines (30,000) . Use a while loop so that you can break as soon as you reach a 0; use Map to store the unique number by making the index/frontnumber the key and make its value an object that serves as a counter to keep track of it's total. If the key exists, update the total; if it doesn't, create a new counter object. Then just return the Map by transforming it into the desired array by map'ing it to an array with only the totals.
var sourceArray = ["001:001", "001:002", "001:003",
"002:001", "002:002",
"003:001", "003:002"
];
function getTotal(sourceArray) {
let count = new Map();
let update = item => count.get(item).total++;
let create = item => count.set(item, {total: 1});
const getItem = index => {
let text = sourceArray[index];
return text.substr(0, 3);
}
let index = -1;
let start = 0;
while (index != 0 && start < sourceArray.length) {
index = getItem(start++);
count.has(index) ? update(index) : create(index);
}
return [...count.values()].map(item => item.total);
}
console.log(getTotal(sourceArray));

How To Get Multiple Array Value Based On Another Array In Javascript

I don't know what must be title for my question, I think it's so complicated. So, I have A array:
["87080207", "87101133", "91140156"]
And B Array:
["97150575", "97150575", "90141063"]
This B array, I put on html select value. Each of them(A and B array) is related. I need to show 87080207,87101133 (A array) when I choose value 97150575 (B array).
I have tried, but it didn't work.This is my code:
var a=[];
var b=[];
var arrayLength = dataComponentValuation.length;
for (var i = 0; i < arrayLength; i++) {
a.push(dataComponentValuation[i].valuated);
b.push(dataComponentValuation[i].valuator);
}
var ajoin = a.join();
var bjoin = b.join();
$('#valuatedEmpCompId_before').val(ajoin);
$('#valuator_before').val(bjoin);
In select, I put a function, this is it:
function emptyValuated() {
var valby = $("#valBy").val(); //chosen value from select
var b_valby = $("#valuator_before").val();
var b_valuated = $("#valuatedEmpCompId_before").val();
if(b_valby != ''){
if(valby != b_valby)
{
$("#valuatedEmpCompId").val('');
}
else{
$("#valuatedEmpCompId").val(b_valuated);
}
}
else{
$("#valuator_before").val(valby);
$("#valuatedEmpCompId").val(b_valuated);
}
}
Help me please...
As suggested, you could use an object as reference to the values of array A.
var arrayA = ["87080207", "87101133", "91140156"],
arrayB = ["97150575", "97150575", "90141063"],
object = Object.create(null);
arrayB.forEach(function (b, i) {
object[b] = object[b] || [];
object[b].push(arrayA[i]);
});
console.log(object);
I guess nowadays the Map object is a perfect solution for these jobs.
var arrayA = ["87080207", "87101133", "91140156"],
arrayB = ["97150575", "97150575", "90141063"],
myMap = arrayB.reduce((p,c,i) => p.has(c) ? p.set(c, p.get(c).concat(arrayA[i]))
: p.set(c,[arrayA[i]])
, new Map());
console.log(myMap.get("97150575"));
console.log(myMap.get("90141063"));

Match two multidimensional array in Javascript

I have two multidimensional array and i want to create a third multidimensional array:
var reports = [
[48.98,153.48],
[12.3,-61.64]
];
var vulc = [
["ciccio",48.98,153.48],
["cicci",12.3,-61.64],
["intruso",59.9,99.9]
];
And i want to create a new multidimensional array
var nuovarray= [];
for (i=0; i<= reports.length; i++) {
var attivi= reports[i];
var attlat= attivi[0];
var attlng= attivi[1];
for (s=0; s<=vulc.length; s++){
var vulca= vulc[s];
var vulcanam= vulca[0];
var vulcalat= vulca[1];
var vulcalng= vulca[2];
if ((vulcalat==attlat) && (vulcalng==attlng){
var stato= "A";
nuovarray.push([vulcanam,vulcalat,vulcalng,stato]);
}
else{
var stato= "N";
nuovaarray.push([vulcanam,vulcalat,vulcalng,stato]);
}
}
}
i would like to have
var nuovarray= [
["ciccio",48.98,153.48,"N"],
["cicci",12.3,-61.64,"N"],
["intruso",59.9,99.9,"A"]
];
But i don't know if this code is good :/
As I said in the comment, in the for loop, use < not <= (array of length N has indexes 0 ... N-1) ... and swap the outer loop with the inner loop, and only push with value 'N' before the end of the outer loop if the inner loop hasn't pushed with value 'A'
var reports = [
[48.98,153.48],
[12.3,-61.64]
];
var vulc = [
["ciccio",48.98,153.48],
["cicci",12.3,-61.64],
["intruso",59.9,99.9]
];
var nuovarray= [];
for(var s = 0; s < vulc.length; s++) {
var vulca = vulc[s];
var stato= "A"; // default, no match
var vulcanam= vulca[0];
var vulcalat= vulca[1];
var vulcalng= vulca[2];
for(var i = 0; i < reports.length; i++) {
var attivi = reports[i];
var attlat= attivi[0];
var attlng= attivi[1];
if ((vulcalat==attlat) && (vulcalng==attlng)) {
stato = "N";
break; // we've found a match, so set stato = N and stop looping
}
}
nuovarray.push([vulcanam,vulcalat,vulcalng,stato]);
}
document.getElementById('result').innerHTML = (nuovarray).toSource();
<div id='result'></div>
I believe the code will not work the way it is written. At least, it will not give you the expected output. You are iterating through the vulc array inside the loop which iterates through reports. And you are pushing to the nuovarray inside the inner loop. So I would expect 6 elements in nuovarray, not the 3 elements you are expecting.
Did you try running it? That's the easiest way to prove incorrectness.
var reports = [
[48.98,153.48],
[12.3,-61.64]
];
var vulc = [
["ciccio",48.98,153.48],
["cicci",12.3,-61.64],
["intruso",59.9,99.9]
];
var nuovarray = [];
vulc.forEach(function(item, indx){
var bN = 'undefined' !== typeof reports[indx];
bN = bN && item[1] == reports[indx][0] && item[2] == reports[indx][1];
item.push(bN ? 'N' : 'A');
nuovarray.push(item);
});
console.log(nuovarray);
The code maps the given vulc to nuovarray and add the wanted flag to it. The flag is selected by a search over reports and if found, an 'N' is applied, otherwise an 'A' is applied.
var reports = [
[48.98, 153.48],
[12.3, -61.64]
],
vulc = [
["ciccio", 48.98, 153.48],
["cicci", 12.3, -61.64],
["intruso", 59.9, 99.9]
],
nuovarray = vulc.map(function (a) {
a.push(reports.some(function (b) {
return a[1] === b[0] && a[2] === b[1];
}) ? 'N' : 'A')
return a;
});
document.getElementById('out').innerHTML = JSON.stringify(nuovarray, null, 4);
<pre id="out"></pre>
The map() method creates a new array with the results of calling a provided function on every element in this array.
Array.prototype.map()
The push() method adds one or more elements to the end of an array and returns the new length of the array.
Array.prototype.push()
The some() method tests whether some element in the array passes the test implemented by the provided function.
Array.prototype.some()
var reports = [
[48.98,153.48],
[12.3,-61.64]
];
var vulc = [
["ciccio",48.98,153.48],
["cicci",12.3,-61.64],
["intruso",59.9,99.9]
];
console.log(vulc.map(function (item, index) {
item.push(reports.some(function (report) {
return report[0] == item[1] && report[1] == item[2];
})?"N":"A");
return item;
}));
If performance matters, you should use something better than O(n^2):
var existingPoints = {};
reports.forEach(function (row) {
existingPoints[row.join()] = true;
});
var nuovarray = vulc.map(function (row) {
var point = row.slice(1, 3).join();
var flag = existingPoints[point] ? 'A' : 'N';
return row.concat([flag]);
});

array object manipulation to create new object

var actual = [
{"country":"UK","month":"JAN","SR":"John P","AC":"24","PR":"2","TR":1240},
{"country":"AUSTRIA","month":"JAN","SR":"Brad P","AC":"64","PR":"12","TR":1700},
{"country":"ITALY","month":"JAN","SR":"Gim P","AC":"21","PR":"5","TR":900},
{"country":"UK","month":"FEB","SR":"John P","AC":"14","PR":"4","TR":540},
{"country":"AUSTRIA","month":"FEB","SR":"Brad P","AC":"24","PR":"12","TR":1700},
{"country":"ITALY","month":"FEB","SR":"Gim P","AC":"22","PR":"3","TR":600},
{"country":"UK","month":"MAR","SR":"John P","AC":"56","PR":"2","TR":1440},
{"country":"AUSTRIA","month":"MAR","SR":"Brad P","AC":"24","PR":"12","TR":700},
{"country":"ITALY","month":"MAR","SR":"Gim P","AC":"51","PR":"5","TR":200}
];
var expect = [
{month:"JAN",val: {"UK":"24","AUSTRIA":"64","ITALY":"21"}},
{month:"FEB",val: {"UK":"14","AUSTRIA":"24","ITALY":"22"}},
{month:"MAR",val: {"UK":"56","AUSTRIA":"24","ITALY":"51"}}
];
I have array of objects which i need to reshape for one other work. need some manipulation which will convert by one function. I have created plunker https://jsbin.com/himawakaju/edit?html,js,console,output
Main factors are Month, Country and its "AC" value.
Loop through, make an object and than loop through to make your array
var actual = [
{"country":"UK","month":"JAN","SR":"John P","AC":"24","PR":"2","TR":1240},
{"country":"AUSTRIA","month":"JAN","SR":"Brad P","AC":"64","PR":"12","TR":1700},
{"country":"ITALY","month":"JAN","SR":"Gim P","AC":"21","PR":"5","TR":900},
{"country":"UK","month":"FEB","SR":"John P","AC":"14","PR":"4","TR":540},
{"country":"AUSTRIA","month":"FEB","SR":"Brad P","AC":"24","PR":"12","TR":1700},
{"country":"ITALY","month":"FEB","SR":"Gim P","AC":"22","PR":"3","TR":600},
{"country":"UK","month":"MAR","SR":"John P","AC":"56","PR":"2","TR":1440},
{"country":"AUSTRIA","month":"MAR","SR":"Brad P","AC":"24","PR":"12","TR":700},
{"country":"ITALY","month":"MAR","SR":"Gim P","AC":"51","PR":"5","TR":200}
];
var outTemp = {};
actual.forEach(function(obj){ //loop through array
//see if we saw the month already, if not create it
if(!outTemp[obj.month]) outTemp[obj.month] = { month : obj.month, val: {} };
outTemp[obj.month].val[obj.country] = obj.AC; //add the country with value
});
var expected = []; //convert the object to the array format that was expected
for (var p in outTemp) {
expected.push(outTemp[p]);
}
console.log(expected);
Iterate through array and create new list
var actual = [
{"country":"UK","month":"JAN","SR":"John P","AC":"24","PR":"2","TR":1240},
{"country":"AUSTRIA","month":"JAN","SR":"Brad P","AC":"64","PR":"12","TR":1700},
{"country":"ITALY","month":"JAN","SR":"Gim P","AC":"21","PR":"5","TR":900},
{"country":"UK","month":"FEB","SR":"John P","AC":"14","PR":"4","TR":540},
{"country":"AUSTRIA","month":"FEB","SR":"Brad P","AC":"24","PR":"12","TR":1700},
{"country":"ITALY","month":"FEB","SR":"Gim P","AC":"22","PR":"3","TR":600},
{"country":"UK","month":"MAR","SR":"John P","AC":"56","PR":"2","TR":1440},
{"country":"AUSTRIA","month":"MAR","SR":"Brad P","AC":"24","PR":"12","TR":700},
{"country":"ITALY","month":"MAR","SR":"Gim P","AC":"51","PR":"5","TR":200}
];
var newList =[], val;
for(var i=0; i < actual.length; i+=3){
val = {};
val[actual[i].country] = actual[i]["AC"];
val[actual[i+1].country] = actual[i+1]["AC"];
val[actual[i+2].country] = actual[i+2]["AC"];
newList.push({month: actual[i].month, val:val})
}
document.body.innerHTML = JSON.stringify(newList);
This is the correct code... as above solution will help you if there are 3 rows and these will be in same sequnece.
Here is perfect solution :
var actual = [
{"country":"UK","month":"JAN","SR":"John P","AC":"24","PR":"2","TR":1240},
{"country":"AUSTRIA","month":"JAN","SR":"Brad P","AC":"64","PR":"12","TR":1700},
{"country":"ITALY","month":"JAN","SR":"Gim P","AC":"21","PR":"5","TR":900},
{"country":"UK","month":"FEB","SR":"John P","AC":"14","PR":"4","TR":540},
{"country":"AUSTRIA","month":"FEB","SR":"Brad P","AC":"24","PR":"12","TR":1700},
{"country":"ITALY","month":"FEB","SR":"Gim P","AC":"22","PR":"3","TR":600},
{"country":"UK","month":"MAR","SR":"John P","AC":"56","PR":"2","TR":1440},
{"country":"AUSTRIA","month":"MAR","SR":"Brad P","AC":"24","PR":"12","TR":700},
{"country":"ITALY","month":"MAR","SR":"Gim P","AC":"51","PR":"5","TR":200}
];
var tmpArray = [];
var obj =[];
for(var k=0; k<actual.length; k++){
var position = tmpArray.indexOf(actual[k].month);
if(position == -1){
tmpArray.push(actual[k].month);
val = {};
for(var i=0; i<actual.length; i++){
if(actual[i].month == actual[k].month){
val[actual[i].country] = actual[i]["AC"];
}
}
obj.push({month: actual[k].month, val:val});
}
}

How do I divide a complex string into 3 seperate arrays?

Here's where I am:
I started with an array...cleaned it up using 'regex'.
Now I have this...each item has three values
mystring = 4|black|cat, 7|red|dog, 12|blue|fish
Here's where I want to be:
I want to end up with three arrays.
array1=("4","7","12")
array2=("black","red","blue")
array3=("cat","dog","fish")
I also want to do this without leaving the page...preferably using javascript
I understand the theory, but I'm getting tangled in the syntax.
I'd use John Resig's famous "search and don't replace" method here, it's perfect for it:
var arr1 = [], arr2 = [], arr3 = [],
mystring = "4|black|cat, 7|red|dog, 12|blue|fish";
mystring.replace(/(\d+)\|([^\|]+)\|([^,]+)/g, function ($0, $1, $2, $3) {
arr1.push($1);
arr2.push($2);
arr3.push($3);
});
Example
You want to use the split() method :
var res = mystring.split(','); //will give you an array of three strings
var subres = res[0].split('|'); //will give you an array with [4, black, cat]
//etc...
Like this?:
var values = mystring.split(',');
var arrays = new Array();
for(var i=0; i < values.length; i++) {
var parts = values[i].split('|');
for(var j = 0; j < parts.length;j++) {
if(!arrays[j]) {
arrays[j] = new Array();
}
arrays[j].push(parts[j]);
}
}
Will give you an array that contains those three arrays.
var str = '4|black|cat, 7|red|dog, 12|blue|fish';
var tmp = str.split(',');
var firstArray = Array();
var secondArray = Array();
var thirdArray = Array();
for( var i in tmp ){
var splitted = tmp[i].split('|');
//alert(true);
firstArray[i]=splitted[0];
secondArray[i]=splitted[1];
thirdArray[i]=splitted[2];
}

Categories

Resources