Create an 2D matrix coordinate (arrays) with null values - javascript

I want to make an 2D 4x4 array of coordinates (X, Y) that its position on the array holds null values. Like main_matrix[0][0] = null ... main_matrix[4, 4] = null but I can't figure how I make this.
I would appreciate this prototype because I want to remake an 2048.
Thanks in advance

You can make a function that creates an array and fills if with values, optionally using a callback, and use that to create the array of arrays:
function createArray(len, value) {
var a = new Array(len), f = typeof value == "function";
for (var i = 0; i < len; i++) a[i] = f ? value() : value;
return a;
}
var main_matrix = createArray(4, createArray.bind(this, 4, null));

main_matrix=[];
for(var i=0;i<4;i++){
main_matrix[i]=[];
for(var j=0;j<4;j++){
main_matrix[i][j]=null;
}
}

Use this implementation:
Array.apply(null, Array(2048)).map(function() { return Array.apply(null, Array(2048)).map(function() { return null }) });
Good luck

Related

Compute value for different properties of object

Given an array of objects
function Example(x, y){
this.prop1 = x;
this.prop2 = y;
}
var exampleArray = new Array();
exampleArray.push(nex Example(0,1));
exampleArray.push(nex Example(1,3));
Now I would like to add a function which computes the average for one of the properties
function calcAvg(exampleArray, 'prop1') -> 0.5
function calcAvg(exampleArray, 'prop2') -> 2
If I don't want to use jQuery or other libraries, is there a generic way to do this?
Solution with Array.prototype.reduce method and check for valid property:
function Example(x, y) {
this.prop1 = x;
this.prop2 = y;
}
var exampleArray = new Array();
exampleArray.push(new Example(0, 1));
exampleArray.push(new Example(1, 3));
function calcAvg(arr, prop) {
if (typeof arr[0] === 'object' && !arr[0].hasOwnProperty(prop)) {
throw new Error(prop + " doesn't exist in objects within specified array!");
}
var avg = arr.reduce(function(prevObj, nextObj){
return prevObj[prop] + nextObj[prop];
});
return avg/arr.length;
}
console.log(calcAvg(exampleArray, 'prop2')); // output: 2
I think it will work ,
You need to iterate through all Example objects in the array and add the given property's value in a variable e.g. sum and then at the end divide it by total number of objects in the array to get average.
console.log(avg(exampleArray, 'prop1'));
function avg (array, propName){
var sum = 0;
array.forEach(function(exm){
sum+= exm[propName];
});
return sum / array.length;
}
You can use Array.prototype.reduce() for it.
The reduce() method applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value.
function Example(x, y) {
this.prop1 = x;
this.prop2 = y;
}
function calcAvg(array, key) {
return array.reduce(function (r, a) {
return r + a[key];
}, 0) / array.length;
}
var exampleArray = [new Example(0, 1), new Example(1, 3)],
avgProp1 = calcAvg(exampleArray, 'prop1'),
avgProp2 = calcAvg(exampleArray, 'prop2');
document.write(avgProp1 + '<br>');
document.write(avgProp2);
This code iterates over every value of arr, searches for property prop in every value, pushes the value of that property to an array named values and returns the sum of all the values in values divided by the number of values in it.
function calcAvg(arr,prop){
var values = [];
for(var i = 0; i<arr.length; i++){
values.push(arr[i][prop]);
}
var sum = values.reduce(function(prev,current){
return prev+current;
});
return sum/values.length;
}
Demo is here.

Check if object excists in javascript array

I'm trying to create an Array with unique objects. I've got json data from a tounament that I want to order by pools. Each match got his own pooldata so he will push the pool data of each match to the array. This will create an Array of 5 of the same pool values. This is my code:
var arr = [];
for (var i = 0; i < data.objects.length; i++){
obj = {
poolId: data.objects[i].pool.id,
poolLetter: data.objects[i].pool.name
};
if (arr.indexOf(obj) == -1) {
arr.push(obj);
}else{}
}
The problem is that the obj you are generating in the loop is not going to be the same object inside your arr array, they will have different signatures, so you can't use indexOf in this instance.
Instead, you will have to loop over the arr array to see if you can find any elements with the same poolId or poolLetter:
var arr = [];
for (var i = 0; i < data.objects.length; i++){
obj = {
poolId: data.objects[i].pool.id,
poolLetter: data.objects[i].pool.name
};
// Do the insert if arr doesn't already contain this poolId
if(!arrayContains(arr, obj.poolId)) arr.push(obj);
}
// Helper function to find an instance of poolId in the given array
function arrayContains(arr, poolId) {
for(var x = 0; x < arr.length; x++) {
if(arr[x].poolId === poolId) {
return true;
}
}
return false;
}
Here is a fiddle which demonstrates the above.
indexOf compares searchElement to elements of the Array using strict equality (the same method used by the ===, or triple-equals, operator).
then
var obj1 = { a:1};
var obj2 = { a:1};
obj1 === obj2; // wrong
when you write "var obj1={a:1}" ,javascript create a new object.
You can use Array Prototype. Just pass the object.
Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) {
if (this[i] === obj) {
return true;
}
}
return false;
}
Use the following
alert([1, 2, 3].contains(2)); //true
alert([1, 2, 3].contains('2')); //false
There is also a jQuery solution. I know you didn't asked for a jQuery answer. But maybe you want use it.
jQuery.inArray() returns the index of a specified value and returns -1 if not found.
http://api.jquery.com/jQuery.inArray/

Is there a more concise way to initialize empty multidimensional arrays?

I've been trying to find a reasonably concise way to set the dimensions of an empty multidimensional JavaScript array, but with no success so far.
First, I tried to initialize an empty 10x10x10 array using var theArray = new Array(10, 10 10), but instead, it only created a 1-dimensional array with 3 elements.
I've figured out how to initialize an empty 10x10x10 array using nested for-loops, but it's extremely tedious to write the array initializer this way. Initializing multidimensional arrays using nested for-loops can be quite tedious: is there a more concise way to set the dimensions of empty multidimensional arrays in JavaScript (with arbitrarily many dimensions)?
//Initializing an empty 10x10x10 array:
var theArray = new Array();
for(var a = 0; a < 10; a++){
theArray[a] = new Array();
for(var b = 0; b < 10; b++){
theArray[a][b] = new Array();
for(var c = 0; c < 10; c++){
theArray[a][b][c] = 10
}
}
}
console.log(JSON.stringify(theArray));
Adapted from this answer:
function createArray(length) {
var arr = new Array(length || 0),
i = length;
if (arguments.length > 1) {
var args = Array.prototype.slice.call(arguments, 1);
while(i--) arr[i] = createArray.apply(this, args);
}
return arr;
}
Simply call with an argument for the length of each dimension.
Usage examples:
var multiArray = createArray(10,10,10); Gives a 3-dimensional array of equal length.
var weirdArray = createArray(34,6,42,2); Gives a 4-dimensional array of unequal lengths.
function multiDimArrayInit(dimensions, leafValue) {
if (!dimensions.length) {
return leafValue;
}
var arr = [];
var subDimensions = dimensions.slice(1);
for (var i = 0; i < dimensions[0]; i++) {
arr.push(multiDimArrayInit(subDimensions, leafValue));
}
return arr;
}
console.log(multiDimArrayInit([2,8], "hi")); // counting the nested "hi"'s yields 16 of them
demo http://jsfiddle.net/WPrs3/
Here is my take on the problem: nArray utility function
function nArray() {
var arr = new Array();
var args = Array.prototype.slice.call(arguments, 1);
for(var i=0;i<arguments[0];i++) {
arr[i] = (arguments.length > 1 && nArray.apply(this, args)) || undefined;
}
return arr;
}
Usage example:
var arr = nArray(3, 3, 3);
Results in 3x3x3 array of undefined values.
Running code with some tests also available as a Fiddle here: http://jsfiddle.net/EqT3r/7/
The more dimension you have, the more you have interest in using one single flat array and a getter /setter function for your array.
Because for a [d1 X d2 X d3 X .. X dn] you'll be creating d2*d3*...*dn arrays instead of one, and when accessing, you'll make n indirection instead of 1.
The interface would look like :
var myNArray = new NArray(10,20,10);
var oneValue = myNArray.get(5,8,3);
myNArray.set(8,3,2, 'the value of (8,3,2)');
the implementation depends on your preference for a fixed-size
n-dimensionnal array or an array able to push/pop and the like.
A more succinct version of #chris code:
function multiDim (dims, leaf) {
dims = Array.isArray (dims) ? dims.slice () : [dims];
return Array.apply (null, Array (dims.shift ())).map (function (v, i) {
return dims.length
? multiDim (dims, typeof leaf == 'string' ? leaf.replace ('%i', i + ' %i') : leaf)
: typeof leaf == 'string' ? leaf.replace ('%i', i) : leaf;
});
}
console.log (JSON.stringify (multiDim ([2,2], "hi %i"), null, ' '));
Produces :
[
[
"hi 0 0",
"hi 0 1"
],
[
"hi 1 0",
"hi 1 1"
]
]
In this version you can pass the first argument as a number for single dimension array.
Including %i in the leaf value will provide index values in the leaf values.
Play with it at : http://jsfiddle.net/jstoolsmith/r3eMR/
Very simple function, generate an array with any number of dimensions. Specify length of each dimension and the content which for me is '' usually
function arrayGen(content,dims,dim1Len,dim2Len,dim3Len...) {
var args = arguments;
function loop(dim) {
var array = [];
for (var a = 0; a < args[dim + 1]; a++) {
if (dims > dim) {
array[a] = loop(dim + 1);
} else if (dims == dim) {
array[a] = content;
}
}
return array;
}
var thisArray = loop(1);
return thisArray;
};
I use this function very often, it saves a lot of time

How to reduce a list of multiple items to a key value pair object in Javascript?

I have an array of states:
['CO','CA','CO','AL', ... ,'NV']
and I'd like to reduce to:
{ 'CO': 9, 'CA':17, 'AL':1, etc}
The value is the number of times each state occurs in the array.
what's the most efficient way to do this?
function compress2dict( raw_arr )
{
var ret={};
for(var i=0;i<raw_arr.length;i++)
{
var item=raw_arr[i];
ret[item]|=0;
ret[item]++;
}
return ret;
}
a = ['CO','BO','CO','CC','CC','CO','CC']
b = compress2dict(a)
b
{'BO':1, 'CC':3, 'CO':3}
You may be interested in array_count_values from PHPJS. Since the PHP array_count_values function does exactly what you want, it stands to reason that the JavaScript port of that function fits.
I expect you just iterate over the array, assign the member values to object property names and the number of occurences as the value:
function toObj(arr) {
var item, obj = {};
for (var i=0, iLen=arr.length; i<iLen; i++) {
item = arr[i];
obj[item]? ++obj[item] : (obj[item] = 1);
}
return obj;
}
Or if you like while loops (sometimes they're faster, sometimes not):
function toObj(arr) {
var item, obj = {}, i = arr.length;
while (i) {
item = arr[--i];
obj[item]? ++obj[item] : (obj[item] = 1);
}
return obj;
}

Sorted a javascript array of objects by an object property

Hay, i have an array of objects and i need to sort them (either DESC or ASC) by a certain property of each object.
Here's the data
obj1 = new Object;
obj1.date = 1307010000;
obj2 = new Object;
obj2.date = 1306923600;
obj3 = new Object;
obj3.date = 1298974800;
obj4 = new Object;
obj4.date = 1306923600;
obj5 = new Object;
obj5.date = 1307096400;
data = [obj1,obj2,obj3,obj4,obj5];
Now, i want to order the data array so that the objects are in order by date.
Can someone help me with this?
Use the Array sort() method
data.sort(function(a, b){
return a.date - b.date;
});
try this:
data.sort(function(a,b){
return a.date - b.date; //to reverse b.date-a.date
});
This solution works with any type of data:
sort_array_by = function(field, reverse, pr){
reverse = (reverse) ? -1 : 1;
return function(a,b){
a = a[field];
b = b[field];
if (typeof(pr) != 'undefined'){
a = pr(a);
b = pr(b);
}
if (a<b) return reverse * -1;
if (a>b) return reverse * 1;
return 0;
}
}
Then, use it like this (reverse sort):
data.sort(sort_array_by('date', true, function(a){
return new Date(a);
}));
As another example, you can sort it by a property of type "integer":
data.sort(sort_array_by('my_int_property', true, function(a){
return parseInt(a);
}));
We have an application using Angular/TypeScript and found it slightly easier on the eyes using an arrow function. In our case, the following code is example of what we have:
data.sort((a, b) => a.SortOrder - b.SortOrder);
Not a huge change but this helps moreso when you have many objects to be sorted.
You can use a custom sort function:
function mySort(a,b) {
return (a.date - b.date);
}
data.sort(mySort);
This is an example of how i use sorting array of objects in ascending order here "array" is array of an object.copy paste in a script tag and understand working through console...
function OBJECT(){
this.PROPERTY1 =Math.floor(Math.random()*10+1) ;
}
OBJECT.prototype.getPROPERTY1=function (){
return(this.PROPERTY1);
}
OBJECT.prototype.setPROPERTY1=function (PROPERTY){
this.PROPERTY1=PROPERTY;
}
var array= new Array();
console.log("unsorted object")
for(var a=0;a<10;a++)
{
array.push(new OBJECT());
console.log(array[a].getPROPERTY1())
}
function sorting() {
for(var i in array){
array[i].setPROPERTY1((array[i].getPROPERTY1()*1))
//that is just for sorting an integer value escape this line if not an
//integer property
}
var arr=new(Array);
var temp1=new(Array);
for(var i in array){
temp1.push(array[i]);
}
var temporary=new(Array)
for(var i in array)
{
var temp = array[i].getPROPERTY1();
arr.push(temp);
}
arr.sort(function(a,b){return a-b});
//the argument above is very important
console.log(arr)
for(var i in arr){
for(var j in temp1)
if(arr[i]==temp1[j].getPROPERTY1())
break;
temporary.push(temp1[j])
temp1.splice(j,1)//just this statement works for me
}
array.length=0;
for(var i in temporary)
{
array.push(temporary[i])
}
}
sorting();
console.log("sorted object")
for(var a=0;a<10;a++)
{
console.log(array[a].getPROPERTY1())
}

Categories