Javascript change format from looping into array format - javascript

I have a loop thats looping through some data and getting some fiel values from it.
for (var i = 0; i < mainData[0].main.length; i++) {
var obj = mainData[0].main[i];
var cars = obj.cars;
console.log(cars);
}
This is returning
26
65
34
12
etc
What I need is to put this in a format so it looks like this:
[26, 65, 34, 12]
How can I do this?

You could just map the result and get an array.
cars = mainData[0].main.map(a => a.cars);
ES5
cars = mainData[0].main.map(function (a) { return a.cars; });

You can try this
var result=[];
for (var i = 0; i < mainData[0].main.length; i++) {
var cars = obj.sub.cars;
result.push(cars);
}
console.log(result);

Print the array directly
If you are trying to print just the array, you can use console.log(array)instead of looping over everything in the array.
for example, assume this is the array.
var primes = [2,3,5,7];
console.log(primes);
will output [2,3,5,7]

Related

Algorithm to sort an array in JS

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);

Javascript 2D array getting each element

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])
}

Filter Javascript array based on first integer of each array item

I have an array like this:
var array = [102,103,104,201,203,204,303,301,302,405,406,408,101];
I want to be able to return an array based upon the first integer of each member of the array like so:
newArray = [101,102,103,104];
The array would be returned based on something similar to this expression:
array[i]/100|0 === j;
where j could be 1,2,3, or 4.
eg. 405/100|0 === 4 // partition into the array starting with 4.
Does anyone know of a way that I could efficiently filter this array into another based on the first number?
I guess this question should be, why can't I use the lodash filter function? does is only work with collections? why do I need to use the JS .filter here?
You could use .filter(), like this:
function filterDigit(array, j) {
return array.filter( x => Math.floor(x/100) == j);
}
var array = [102,103,104,201,203,204,303,301,302,405,406,408,101];
var newArray = filterDigit(array, 1);
console.log(newArray);
You could divide the numbers by 100 and use it as index for the result array.
var array = [102, 103, 104, 201, 203, 204, 303, 301, 302, 405, 406, 408, 101],
result = [];
array.sort(function (a, b) { return a - b; });
array.filter(function (a) {
var index = Math.floor(a / 100) - 1;
result[index] = result[index] || [];
result[index].push(a);
});
console.log(result);
Create a list with sublists like this
var PARTISION_DIVISOR = 100
var array = [102,103,104,201,203,204,303,301,302,405,406,408,101];
array.sort()
var new_list = []
for (var i = 0; i<array.length; i++) {
sub_index = (array[i] / PARTISION_DIVISOR)
sub_index = Math.floor(sub_index)
new_list[sub_index] = new_list[sub_index] || []
new_list[Math.floor(sub_index)].push(array[i])
}
new_list
Check out working example https://repl.it/ExSY

Sort array by order according to another array

I have an object that is being returned from a database like this: [{id:1},{id:2},{id:3}]. I have another array which specified the order the first array should be sorted in, like this: [2,3,1].
I'm looking for a method or algorithm that can take in these two arrays and return [{id:2},{id:3},{id:1}]. Ideally it should be sort of efficient and not n squared.
If you want linear time, first build a hashtable from the first array and then pick items in order by looping the second one:
data = [{id:5},{id:2},{id:9}]
order = [9,5,2]
hash = {}
data.forEach(function(x) { hash[x.id] = x })
sorted = order.map(function(x) { return hash[x] })
document.write(JSON.stringify(sorted))
function sortArrayByOrderArray(arr, orderArray) {
return arr.sort(function(e1, e2) {
return orderArray.indexOf(e1.id) - orderArray.indexOf(e2.id);
});
}
console.log(sortArrayByOrderArray([{id:1},{id:2},{id:3}], [2,3,1]));
In your example, the objects are initially sorted by id, which makes the task pretty easy. But if this is not true in general, you can still sort the objects in linear time according to your array of id values.
The idea is to first make an index that maps each id value to its position, and then to insert each object in the desired position by looking up its id value in the index. This requires iterating over two arrays of length n, resulting in an overall runtime of O(n), or linear time. There is no asymptotically faster runtime because it takes linear time just to read the input array.
function objectsSortedBy(objects, keyName, sortedKeys) {
var n = objects.length,
index = new Array(n);
for (var i = 0; i < n; ++i) { // Get the position of each sorted key.
index[sortedKeys[i]] = i;
}
var sorted = new Array(n);
for (var i = 0; i < n; ++i) { // Look up each object key in the index.
sorted[index[objects[i][keyName]]] = objects[i];
}
return sorted;
}
var objects = [{id: 'Tweety', animal: 'bird'},
{id: 'Mickey', animal: 'mouse'},
{id: 'Sylvester', animal: 'cat'}],
sortedIds = ['Tweety', 'Mickey', 'Sylvester'];
var sortedObjects = objectsSortedBy(objects, 'id', sortedIds);
// Check the result.
for (var i = 0; i < sortedObjects.length; ++i) {
document.write('id: '+sortedObjects[i].id+', animal: '+sortedObjects[i].animal+'<br />');
}
To my understanding, sorting is not necessary; at least in your example, the desired resulting array can be generated in linear time as follows.
var Result;
for ( var i = 0; i < Input.length; i++ )
{
Result[i] = Input[Order[i]-1];
}
Here Result is the desired output, Input is your first array and Order the array containing the desired positions.
var objArray = [{id:1},{id:2},{id:3}];
var sortOrder = [2,3,1];
var newObjArray = [];
for (i in sortOrder) {
newObjArray.push(objArray[(sortOrder[i]) - 1])
};
Why not just create new array and push the value from second array in?? Correct me if i wrong
array1 = [];
array2 = [2,3,1];
for ( var i = 0; i < array2 .length; i++ )
{
array1.push({
id : array2[i]
})
}

JavaScript: Transforming a multi-dimensional array into a two dimensional array

I have a JS array that's filled with data as follows:
var myarr = [[new Date("2011-12-01"), 389, 380.75, 382.54, 387.93],
[new Date("2011-11-30"), 382.28, 378.3, 381.29, 382.2]...]
Is there some way to only select the entire date column and the last number of each row? I'm looking for an output that's something like this:
[[new Date("2011-12-01"), 387.93],[new Date("2011-11-30"), 382.2]...]
var myCollapsedArr = [[myarr[0][0], myarr[0][myarr[0].length-1]], [myarr[1][0], myarr[1][myarr[1].length-1]];
Or in a for loop:
var myCollapsedArr = [];
for(var i = 0; i<myarr.length; i++) {
myCollapsedArr.push([myarr[i], [myarr[i][myarr[i].length-1]]);
}
Option 1 - Simple for Loop
// Create array to hold new values
var newArray = [];
// Loop through existing array and pull out data
for(var i = 0; i < myarr.length; i++) {
newArray.push([myarr[i][0], myarr[i][myarr[i].length - 1]]);
}
Here's a working fiddle to demonstrate.
Option 2 - ECMAScript 5 forEach()
// Create array to hold new values
var newArray = [];
// Loop through existing array and pull out data
myarr.forEach(function(obj) {
newArray.push([obj[0], obj[obj.length - 1]]);
});
​Here's a working fiddle to demonstrate.

Categories