repl.it
@mcuringa/

Array-Examples

ES6

#thinkjs #arrays #examples #videos

fork
loading
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
// Example 1: oddCount
// Write a function to count how many odd
// numbers are in an array.

function oddCount(numbers) {
  let counter = 0;

  for (let i = 0; i < numbers.length; i++) {
    if (numbers[i] % 2 !== 0) {
      counter++;
    }
  }
  return counter;
}

// Example 2: sumEvens
// Sum up all the even numbers in an array.

function sumEvens(numbers) {

  let total = 0;
  for (let i = 0; i < numbers.length; i++) {
    if (numbers[i] % 2 === 0) {
      total += numbers[i];
    }
  }

  return total;
}

// Example 3: findNegatives
// Return an array with all of the negative numbers
// in an array. Do not modify the original array
// (i.e. write a pure function).
function findNegatives(numbers) {

  let negatives = [];
  for (let i = 0; i < numbers.length; i++) {
    if (numbers[i] < - 0) {
      negatives.push(numbers[i]);
    }
  }

  return negatives;
}

// Example 4: sumUpToEven
// Sum all the elements in an array up to but 
// not including the first even number.
function sumUpToEven(numbers) {

  let total = 0;
  for (let i = 0; i < numbers.length; i++) {
    if (numbers[i] % 2 === 0) {
      return total;
    }
    total += numbers[i];
  }

  return total;
}

// Example 5: olympicScores

// Write a function that takes an array of numbers and
// returns the an array of numbers with the highest and
// lowest scores removed. Do not modify the original
// array parameter.

function olympicScores(scores) {

  let low = 11;
  let high = 0;
  let lowIx = 0;
  let highIx = 0;

  for (let i = 0; i < scores.length; i++) {
    let score = scores[i];
    if(score > high) {
      high = score;
      highIx = i;
    }
    if(score < low) {
      low = score;
      lowIx = i;
    }
  }
  let ss = scores.slice();
  ss.splice(lowIx, 1);
  ss.splice(highIx, 1);

  return ss;
}

let scores = [10, 8, 8, 9, 5, 10];
let modScores = olympicScores(scores); //=>[8, 8, 9, 10]
console.log("Original scores:", scores);
console.log("Modified scores:", modScores);
Babel Compiler v6.4.4 Copyright (c) 2014-2015 Sebastian McKenzie
?