array.reduce EXAMPLES Flashcards

1
Q

const numbers = [1,2,3];

ADD NUMBERS with REDUCE

console.log(x);// 6

A

numbers.reduce((accumulator, currentValue)=> accumulator + currentValue);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

const numbers = [ {x:1}, {x:2}, {x:3} ];

ADD NUMBERS with REDUCE
var sum = [{x: 1}, {x: 2}, {x: 3}].reduce

console.log(x);// 6

A

var initialValue = 0;
((accumulator, currentValue)
=> accumulator + currentValue.x;
,initialValue);

console.log(sum) // logs 6

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

const numbers = [[1,2],[3,4]];

Flatten array

console.log(x);// [1, 2, 3, 4];

A

numbers.reduce((a, b) a.concat(b));

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

const numbers = [[1],[3,4]];

let x = numbers.reduce((accumulator, currentValue)=> accumulator + currentValue);

console.log(x);// returns

A

13, 4

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

var names = [‘Alice’, ‘Bob’, ‘Tiff’, ‘Bruce’, ‘Alice’];

var countedNames = 
//Counting instances of values in an object
// countedNames is:
// { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }
A
names.reduce(function (allNames, name) { 
  if (name in allNames) {
    allNames[name]++;
  }
  else {
    allNames[name] = 1;
  }
  return allNames;
}, {});
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q
var myArray = ['a', 'b', 'a', 'b', 'c', 'e', 'e', 'c', 'd', 'd', 'd', 'd'];
var myOrderedArray = 
//Remove duplicate items in array

console.log(myOrderedArray);

A

myArray.reduce(function (accumulator, currentValue) {
if (accumulator.indexOf(currentValue) === -1) {
accumulator.push(currentValue);
}
return accumulator
}, [])

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q
const numbers = [1,2,3];
numbers.reduce((accumulator, currentValue)=> accumulator + currentValue);

//WRITE OUT OLD WAY

let sum =

A

let sum = 0;
for (let n of numbers)
sum+= n;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

WHY DOES THIS RETURN AN ARRAY

const numbers = [1, 2, 3];

function sum(...arg){
console.log(arg);
return arg.reduce((a, cv) => a + cv);
};

console.log(sum([1,2,3]));

A

…arg turns an array into an array.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

const numbers = [1, 2, 3];

function sum(...arg){
// Write the If statement to check to see if arg is an array and set it to a array

return arg.reduce((a, cv) => a + cv);
};

console.log(sum([1]));

A

if (Array.isArray(arg[0]))

arg = […arg[0]];

How well did you know this?
1
Not at all
2
3
4
5
Perfectly