Some Array Methods

var newArray= Array.from(oldArray);

var newArray = oldArray.slice(); 

Makes a new copy of the old array instead of just referencing it.


Array.isArray(input); 

Checks if a value is an array.


arr.slice(begin, end);

Extracts a portion of an array based on provided indices. (Omitting begin will default it to index 0.  Omitting end will default to extracting up to the end arr.length).


arr.splice(startIndex, deleteCount, ‘item1‘, item2‘, etc.);

Remove or insert element where start is.  (Set deleteCount to 0 if you’re inserting).

Advertisements
Some Array Methods

JavaScript Objects

Object.keys(obj) returns an array of keys in a hash object.

Examples:

var arr = ['a', 'b', 'c'];
console.log(Object.keys(arr)); // console: ['0', '1', '2']

// array like object
var obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.keys(obj)); // console: ['0', '1', '2']

// array like object with random key ordering
var an_obj = { 100: 'a', 2: 'b', 7: 'c' };
console.log(Object.keys(an_obj)); // console: ['2', '7', '100']

Object.values(obj) returns an array of values in a hash object.

Examples:

var obj = { foo: 'bar', baz: 42 };
console.log(Object.values(obj)); // ['bar', 42]

// array like object
var obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.values(obj)); // ['a', 'b', 'c']

// array like object with random key ordering
var an_obj = { 100: 'a', 2: 'b', 7: 'c' };
console.log(Object.values(an_obj)); // ['b', 'c', 'a']

obj.hasOwnProperty(prop) returns true/false indicating if an object has the specified property (key, NOT value).

Examples:

var object = {cat: 'meow'};
object.hasOwnProperty('cat'); // true
object.hasOwnProperty('meow'); // false

To access a property’s value:  object[key]

Example:  object['cat']; // 'meow'

JavaScript Objects

Hackerrank Day 1: Interquartile Range

screen-shot-2016-12-29-at-10-31-35-pm

screen-shot-2016-12-29-at-10-30-50-pm

My Solution in Ruby:

screen-shot-2016-12-29-at-10-29-31-pm

We can also store the elements and their corresponding frequencies in their own hash, which are stored in an array, and sort the array by the value of the element in the hashes, like so:

screen-shot-2016-12-29-at-11-28-28-pm

  • It’s possible to store hashes within an array.
  • sort! modifies current existing array.  sort creates a new sorted array.
    • array.sort!{ |x, y| x <=> y }  sorts current array in ascending order.
    • array.sort!{ |x, y| y <=> x }  sorts current array in descending order.
  • Array.new that takes two arguments (n, element) returns that element n times.
    • Array.new(3, true) #=> [true, true, true]

 

Hackerrank Day 1: Interquartile Range