kaniosrn-j
11/27/2017 - 11:20 AM

Arrays - Ref

var numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

// inserting an elements
numbers.push(11);
numbers.push(12, 13);

// Insert an element in the first position
  // hard way
  for (var i = numbers.length; i >= 0; i--) {
    numbers[i] = numbers[i - 1]
  }
  numbers[0] = -1;

  // easy way
  numbers.unshift(-2);
  numbers.unshift(-4, -3);


// removing elements
numbers.pop();

// Removing an element from first position
// hard way
for (var i = 0; i < numbers.length; i++) {
  numbers[i] = numbers[i + 1];
}
// easy way
numbers.shift();

// Adding and remove element from specific position
// ex 1
numbers.splice(5, 3);

// ex 2  - this will remove three elements, starting from the index 5, and also adding the element 2,3,4, starting at in dex 5
numbers.splice(5, 3, 2, 3, 4);

// Two-dimensional and multidimensional arrays
var averageTempDay1 = [72, 75, 79, 79, 81, 81];
var averageTempDay2 = [81, 79, 75, 75, 73, 72];

var averageTemp = [];
averageTemp[0] = [72, 75, 79, 79, 81, 81];
averageTemp[1] = [81, 79, 75, 75, 73, 72];

// day 1
averageTemp[0] = [];
averageTemp[0][0] = 72;
averageTemp[0][1] = 75;
averageTemp[0][2] = 79;
averageTemp[0][3] = 79;
averageTemp[0][4] = 81;
averageTemp[0][5] = 81;
// day 2;
averageTemp[1] = [];
averageTemp[1][0] = 81;
averageTemp[1][1] = 79;
averageTemp[1][2] = 75;
averageTemp[1][3] = 75;
averageTemp[1][4] = 73;
averageTemp[1][5] = 72;

// Iterating the elements of two-dimensional array
function printMatrix (myMatrix) {
  for (var i = 0; i < myMatrix.length; i++) {
    for (var j = 0; j < myMatrix[i].length; j++) {
      console.log(myMatrix[i][j]);
    }
  }
}
printMatrix(averageTemp);

// Multi-dimensional arrays
var matrix3x3x3 = [];

for (var i = 0; i < 3; i++) {
  matrix3x3x3[i] = [];
  for (var j = 0; j < 3; j++) {
    matrix3x3x3[i][j] = [];
    for (var z = 0; z < 3; z++) {
      matrix3x3x3[i][j][z] = i + j + z;
    }
  }
}

// To output the content of this matrix
for (var i = 0; i < matrix3x3x3.length; i++) {
  for (var j = 0; j < matrix3x3x3[i].length; j++) {
    for (var z = 0; z < matrix3x3x3[i][j].length; z++) {
      console.log(matrix3x3x3[i][j][z]);
    }
  }
}

// Joining multiple arrays
var zero = 0;
var positiveNumbers = [1, 2, 3];
var negativeNumbers = [-3, -2, -1];
var numbers = negativeNumbers.concat(zero, positiveNumbers);



// checking even numbers, 2(even) and false otherwise
var isEven = function (x) {
    // returns true if x is a multiple of 2.
    console.log(x);
    return (x % 2 == 0)   true : false;
};
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
return (x % 2 == 0)  ? true : false;