javascript multi array push - javascript

Is it possible to make a multidimensional array in javascript?
It should look like this:
$cars = array
(
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
But I need to use $cars.push(); to first add all data for the first rows (the cars). Then the data "22", "15", "5" and "17". Then "18", "13", "2" and "15".
Then it should be printed in the same order as the original array (table-view).
EDIT
LIKE this:
var cars = [];
cars.push("Volvo", "BMW", "Saab", "Land Rover");
cars.push(22, 15, 5, 17);
cars.push(18, 13, 2, 15);
and print it like this to html
Volvo, 22, 18
BMW, 15 13
Saab, 5, 2
Land Rover, 17, 15

You could refer the documentation.
As #sampson suggested in the comment above in your case it is,
var cars = [
[ "Volve", 22, 18 ],
[ "BMW", 15, 13 ],
[ "Saab", 5, 2],
[ "Land Rover", 17, 15]
];

Is it possible to make a multidimensional array in javascript?
Yes, it is.
But that doesn't seem to be your question. Rather, your question seems to be, if I have an array of arrays, where the first subarray contains values for field 1, the second subarray contains values for field 2, and so on, then how do I re-organize this into in array of arrays where each subarray contains all fields for one object.
As another responder mentioned, this is array transposition. A simple way is:
function transpose(a) {
return a[0] . map((col, i) => a . map(row => row[i]));
}
Use this as:
var cars = [];
cars.push(["Volvo", "BMW", "Saab", "Land Rover"]);
cars.push([22, 15, 5, 17]);
cars.push([18, 13, 2, 15]);
console.log(transpose(cars));

You can rebuild the array with the change of position i and j. And you can switch it from one appearance to the other one.
function transpose(source, target) {
source.forEach(function (a, i) {
a.forEach(function (b, j) {
target[j] = target[j] || []
target[j][i] = b;
});
});
}
var cars = [["Volvo", 22, 18], ["BMW", 15, 13], ["Saab", 5, 2], ["Land Rover", 17, 15]],
pCars = [];
transpose(cars, pCars);
document.write('<pre>' + JSON.stringify(pCars, 0, 4) + '</pre>');
cars = [];
transpose(pCars, cars);
document.write('<pre>' + JSON.stringify(cars, 0, 4) + '</pre>');

Related

Prevent arrray.map returning undefined when condition/callback is not met [duplicate]

This question already has answers here:
How to skip over an element in .map()?
(18 answers)
Map and filter an array at the same time
(16 answers)
Closed 1 year ago.
I was writing some code and something puzzled me. I have an array of numbers called alarmsList. Now I wish to iterate through this list and if a value is higher than 60 for example I want to create a new object array (collection) where we store the high value and it's index from the original array. So take the following code
const alarmsList = [1, 61, 77, 4, 5, 6, 7, 8, 85, 4, 3, 55];
const highAlarmsList = alarmsList.map((item, index) => {
if(item > 60) {
return ({ value: item, index })
}
});
console.log(highAlarmsList)
The console.log outputs the following
[
undefined,
{
"value": 61,
"index": 1
},
{
"value": 77,
"index": 2
},
undefined,
undefined,
undefined,
undefined,
undefined,
{
"value": 85,
"index": 8
},
undefined,
undefined,
undefined
]
This output is what I require but how do I prevent the undefined values being returned? I thought about using array.filter but that doesn't seem appropriate? Should I use a different array method? I don't want to use a for loop and push to a new array unless that is the best/only way to achieve the new array without the undefined values being returned.
You can use Array.filter() to removing the undefined values by using Boolean as the predicate:
const alarmsList = [1, 61, 77, 4, 5, 6, 7, 8, 85, 4, 3, 55];
const highAlarmsList = alarmsList.map((item, index) => {
if(item > 60) {
return ({ value: item, index })
}
}).filter(Boolean);
console.log(highAlarmsList)
You can use Array.flatMap() and return empty arrays instead of undefined, but that might effect performance for huge arrays:
const alarmsList = [1, 61, 77, 4, 5, 6, 7, 8, 85, 4, 3, 55];
const highAlarmsList = alarmsList.flatMap((item, index) =>
item > 60 ? { value: item, index } : []
);
console.log(highAlarmsList)
map creates a new array by running the callback on every element of the array. If the condition does not satisfy it will return undefined or null. So it not possible to skip the element from the output.
Alternatively you can ue reduce or filter
const alarmsList = [1, 61, 77, 4, 5, 6, 7, 8, 85, 4, 3, 55];
const highAlarmsList = alarmsList.reduce((acc, item, index) => {
item > 60 && acc.push({
value: item,
index
})
return acc;
}, [])
console.log(highAlarmsList)

Converting Array to object without any key or single key

I just want to create an object which contains all the values of an array on a sigle key .
arr1 = [{ x: 12, y:13},{ x1: 14, y2:15}];
arr2 = [{ xx: 18, yy:18},{ xx1: 17, yy2:16}];
// result = { finalObj :[{ x: 12, y:13},{ x1: 14, y2:15}],[{ xx: 18, yy:18},{ xx1: 17, yy2:16}]}
Although i can get final array by :
const finalArr = arr1.concat(arr2);
But how to get the end result .
Thanks in advance .
Concat two arrays
{ finalObj: [...arr1, ...arr2] }

How to sort just a specific part of an already sorted 2D Array depending on new values. But only if the first sorted values match in Javascript

I have the following problem:
I have an array with objects in it.
Every object has a score and a rank, like this:
[
{ "score": 20, "rank": 12 },
{ "score": 20, "rank": 7 },
{ "score": 34, "rank": 4 }
]
First of all, I sort this descending by the score and store it into a 2-dimensional array.
[34, 4]
[20, 12]
[20, 7]
But now, if there is the same score twice or more often I want those to be sorted by the rank. So whatever has the lowest rank will have a smaller index number. Resulting in:
[34, 4]
[20, 7]
[20, 12]
I really don't know how to do this, I made some approaches, but they are a way to bad to mention them.
You can check if the difference of score of two objects is 0 then return the difference of rank otherwise return difference of score
const arr = [
{ "score": 20, "rank": 12 },
{ "score": 20, "rank": 7 },
{ "score": 34, "rank": 4 }
]
let res = [...arr]
.sort((a,b) => (b.score - a.score) || (a.rank - b.rank))
.map(x => [x.score,x.rank]);
console.log(res)
Just use lodash and orderby 2 fields.
You could sort the array first and then just map over for the Object.values:
const arr = [
{ "score": 20, "rank": 12 },
{ "score": 20, "rank": 7 },
{ "score": 34, "rank": 4 }
]
let result = arr.sort((a,b) => (b.score - a.score) || (a.rank - b.rank))
.map(x => Object.values(x))
console.log(result)

Find the average of each index in 2+ arrays to return a new array of averages

For this problem, what is the most ideal solution in JavaScript to take a bunch of arrays all with the same number of indexes which all have integer values and then return one array with the average of each index from each array.
Here is an example of what I mean:
var data = [[ 12, 14, 13, 10 ], [ 11, 13, 12, 2 ], [ 18, 12, 3, 4 ]];
to return one single array with all the averages calculated like so:
[13.6, 13, 9.3, 5.3 ];
data=data.map(arr=>arr.reduce((old,new)=>old+new,0)/arr.length);
I dont give an explanation, i give the OP the ability to find out alone + learn it that way...
You have to use map function in order to calculate average for every item from array.I'm using reduce function in order to calculate the sum for every item.
Here is solution:
var data = [[ 12, 14, 13, 10 ], [ 11, 13, 12, 2 ], [ 18, 12, 3, 4 ]];
console.log(data.map(function(item){
return item.reduce( ( prev, current ) => prev + current , 0 ) / item.length;
}));

Javascript get value from array error

I need some help! Im retrieving some values from mySQL database using an external 'grabber'.
<?php
$datapiechart = file_get_contents("url which retrieves the values from MySQL");
?>
Which results in:
[{ "Name1": 62, "Name2": 42, "Name3": 19, "Name4": 7, "Name5": 6, "Name6": 4, "Name7": 1, "Name8": 4, "Name9": 3, "Name10": 1, "Name11": 1, "Name12": 0 }]
Then I want to select the values in this array.
<SCRIPT>
dataObjectdatapiechart = <?php echo $datapiechart; ?>
</SCRIPT>
<script> dataObjectdatapiechart.Name1</script>
I don't get whats going wrong here.
dataObjectdatapiechart is an array (with only one element), so you need to access it's contents using an indexer:
var item = dataObjectdatapiechart[0]; // Retrieve the object from the array
var name1 = item.Name1;
var name2 = item.Name2;
var name3 = item.Name3;
//etc.
Use
dataObjectdatapiechart[0].Name1
The Object { "Name1": 62, "Name2": 42, "Name3": 19, "Name4": 7, "Name5": 6, "Name6": 4, "Name7": 1, "Name8": 4, "Name9": 3, "Name10": 1, "Name11": 1, "Name12": 0 }
is at 0th position of the array.

Categories