Skip to content

Instantly share code, notes, and snippets.

@nicobytes
Last active April 21, 2020 23:14
Show Gist options
  • Select an option

  • Save nicobytes/3b808442364a1e13ac668d648977e4e7 to your computer and use it in GitHub Desktop.

Select an option

Save nicobytes/3b808442364a1e13ac668d648977e4e7 to your computer and use it in GitHub Desktop.
Arrays

Arrays

Why?

const averageTempJan = 31.9;
const averageTempJan = 35.3;
const averageTempMar = 42.4;
const averageTempApr = 52;
const averageTemp = [];
averageTemp[0] = 31.9;
averageTemp[1] = 35.3;
averageTemp[2] = 42.4;
averageTemp[3] = 52;

Create

const array1 = new Array();
const array2 = new Array(1,2,3,4,5);
const array3 = [];
const array3 = [1,2,3,4,5];

Get elements

const numbers = [1,2,3,4,5];
for (let index = 0; index < numbers.length; index++) {
  console.log(numbers[index], index);
}
const fibonacci = [];
fibonacci[0] = 0;
fibonacci[1] = 1;
fibonacci[2] = 1;
for (let index = 3; index < 20; index++) {
  fibonacci[index] = fibonacci[index - 1] + fibonacci[index - 2];
}
console.log(fibonacci);

Add an element at end

const numbers = [1,2,3,4,5];
numbers[numbers.length] = 6;
numbers.push(7);

Add an element in the fisrt

const numbers = [0,1,2,3,4,5];
for (let index = numbers.length; index >= 0; index--) {
  numbers[index] = numbers[index - 1];
}
numbers[0] = -1;
numbers.unshift(-2);

Remove elements the first element

const numbers = [0,1,2,3,4,5];
for (let index = 0; index < numbers.length; index++) {
  numbers[index] = numbers[index + 1];
}
const numbers = [0,1,2,3,4,5];

const newArray = [];
for (let index = 0; index < numbers.length; index++) {
  const value = numbers[index + 1];
  if (value !== undefined) {
    newArray.push(value);
  }
}
numbers.shift();

Add and remove elements from specific position

const numbers = [0,1,2,3,4,5];
numbers.splice(3,1);
numbers.splice(5,0,1);

multi-demensional

const multi = [
  [1,1],
  [2,2],
  [3,3]
];
console.table(multi);

map, filter y reduce

sort

const numbers = [0,1,2,3,4,5];
numbers.reverse()
numbers.sort()
numbers.sort((a,b) => a - b)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment