はじめに
JSchallenger の Javascript Fundamentals – Javascript Arrays のまとめです。
まとめページのトップは、JSchallenger まとめ です。
問題一覧と回答
Get nth element of array
// Write a function that takes an array (a) and a value (n) as argument
// Return the nth element of ‘a’
function myFunction(a, n) {
return a[n - 1];
}
Remove first n elements of an array
// Write a function that takes an array (a) as argument
// Remove the first 3 elements of ‘a’
// Return the result
function myFunction(a) {
return a.slice(3);
}
Get last n elements of an array
// Write a function that takes an array (a) as argument
// Extract the last 3 elements of ‘a’
// Return the resulting array
function myFunction(a) {
return a.slice(-3);
}
Get first n elements of an array
// Write a function that takes an array (a) as argument
// Extract the first 3 elements of a
// Return the resulting array
function myFunction(a) {
return a.slice(0, 3);
}
Return last n array elements
// Write a function that takes an array (a) and a number (n) as arguments
// It should return the last n elements of a
function myFunction(a, n) {
return a.slice(-n);
}
Remove a specific array element
// Write a function that takes an array (a) and a value (b) as argument
// The function should remove all elements equal to ‘b’ from the array
// Return the filtered array
function myFunction( a, b ) {
return a.filter(cur => cur !== b)
}
Count number of elements in JavaScript array
// Write a function that takes an array (a) as argument
// Return the number of elements in a
function myFunction(a) {
return a.length;
}
Count number of negative values in array
// Write a function that takes an array of numbers as argument
// Return the number of negative values in the array
括弧はいるのか?
function myFunction(a) {
return a.filter( v => v < 0 ).length;
}
function myFunction(a) {
return a.filter((el) => el < 0).length;
}
Sort an array of strings alphabetically
// Write a function that takes an array of strings as argument
// Sort the array elements alphabetically
// Return the result
function myFunction( arr ) {
return arr.sort()
}
Sort an array of numbers in descending order
// Write a function that takes an array of numbers as argument
// It should return an array with the numbers sorted in descending order
function myFunction( arr ) {
return arr.sort((a, b) => b - a)
}
Calculate the sum of an array of numbers
// Write a function that takes an array of numbers as argument
// It should return the sum of the numbers
function myFunction(a) {
return a.reduce((acc, cur) => acc + cur, 0);
}
Return the average of an array of numbers
// Write a function that takes an array of numbers as argument
// It should return the average of the numbers
function myFunction( arr ) {
return arr.reduce((acc, cur) => acc + cur, 0) / arr.length
}
Return the longest string from an array of strings
// Write a function that takes an array of strings as argument
// Return the longest string
function myFunction( arr ) {
return arr.reduce((a, b) => a.length <= b.length ? b : a)
}
Check if all array elements are equal
// Write a function that takes an array as argument
// It should return true if all elements in the array are equal
// It should return false otherwise
function myFunction( arr ) {
returnnewSet(arr).size === 1
}
Merge an arbitrary number of arrays
// Write a function that takes arguments an arbitrary number of arrays
// It should return an array containing the values of all arrays
flat 知らんかった。
function myFunction(...arrays) {
return arrays.reduce((sum, cur) => [...sum, ...cur], []);
}
function myFunction( ...arrays ) {
return arrays.flat()
}
Sort array by object property
// Write a function that takes an array of objects as argument
// Sort the array by property b in ascending order
// Return the sorted array
これは連結した方が分かりやすいだろう
function myFunction(arr) {
return arr.sort((a, b) => a.b - b.b);
}
function myFunction(arr) {
constsort = (x, y) => x.b - y.b;
return arr.sort(sort);
}
Merge two arrays with duplicate values
// Write a function that takes two arrays as arguments
// Merge both arrays and remove duplicate values
// Sort the merge result in ascending order
// Return the resulting array
Set で array 2つで初期化する方法が思いつかんかった(/_\*)
function myFunction(a, b) {
s = newSet(a);
b.map(v => s.add(v));
return [...s].sort((a, b) => a - b);
}
function myFunction(a, b) {
return [...newSet([...a, ...b])].sort((x, y) => x - y);
}
Sum up all array elements with values greater than
// Write a function that takes an array (a) and a number (b) as arguments
// Sum up all array elements with a value greater than b
// Return the sum
function myFunction(a, b) {
return a.reduce((sum, cur) => cur > b ? sum + cur : sum, 0);
}
function myFunction(a, b) {
return a.reduce((sum, cur) => {
if (cur > b) return sum + cur;
return sum;
}, 0);
}
Create a range of numbers
// Write a function that takes two numbers (min and max) as arguments
// Return an array of numbers in the range min to max
これ、author’s solution と同じ方法しか思いつかなかったけども、いい方法ないのかな。
Perl なら min…max
で終わりなのだが。
function myFunction(min, max) {
let arr = [];
for (let i = min; i <= max; i++) {
arr.push(i);
}
return arr;
}
Group array of strings by first letter
// Write a function that takes an array of strings as argument
// Group those strings by their first letter
// Return an object that contains properties with keys representing first letters
// The values should be arrays of strings containing only the corresponding strings
// For example, the array [‘Alf’, ‘Alice’, ‘Ben’] should be transformed to
// { a: [‘Alf’, ‘Alice’], b: [‘Ben’]}
上手いやり方作れず泥臭い方法しか思いつかなかった。。
author’s solution のように return できるとキレイだけど、わかりにくい気も。
function myFunction(arr) {
return arr.reduce((sum, cur) => {
const k = cur[0].toLowerCase();
if (sum[k]) {
sum[k].push(cur);
}
else {
sum[k] = [cur];
}
return sum;
}, {});
}
function myFunction(arr) {
return arr.reduce((acc, cur) => {
const firstLetter = cur.toLowerCase().charAt(0);
return { ...acc, [firstLetter]: [...(acc[firstLetter] || []), cur] };
}, {});
}
Define an array with conditional elements
// Write a function that takes an array with arbitrary elements and a number as arguments
// Return a new array, the first element should be either the given number itself
// or zero if the number is smaller than 6
// The other elements should be the elements of the original array
// Try not to mutate the original array
問題文が “smaller than 6” なのに num > 5
とコードを書くのは違和感がある。
function myFunction(arr, num) {
return [...[num < 6 ? 0 : num], ...arr];
}
function myFunction(arr, num) {
return [...(num > 5 ? [num] : [0]), ...arr];
}
Get every nth element of array
// Write a function that takes an array (a) and a value (n) as arguments
// Save every nth element in a new array
// Return the new array
これも愚直な方法で解いたけども、author’s solution はもっと愚直だったw
もっと美しい解法ないのかな。
function myFunction(a, n) {
r = [];
for (i = n - 1; i <= a.length; i += n) {
r.push(a[i]);
}
return r;
}
function myFunction(a, n) {
let rest = [...a];
let result = [];
for (let i = 0; i < a.length; i++) {
if (rest.length < n) break;
result.push(rest[n - 1]);
rest = rest.slice(n);
}
return result;
}
コメント