Node.js 面试题目
// given an array
const arr = [1, 2, 3, 5, 6, 7, 4, 1];
// find a sum of (all numbers that are bigger or equal to 3)
const result = arr.filter((item) => item >= 3).reduce((a, b) => a + b);
console.log(result);
// given a string
const str = 'one two three two one one four five';
// return a count of duplicate words in that string
function countDuplicates(strVal) {
const strArray = str.split(" ");
const dictCount = {};
for (const key of strArray) {
if (!dictCount[key]) {
dictCount[key] = 1;
continue;
}
dictCount[key]++;
}
console.log(dictCount);
let result = 0;
for (const key of Object.keys(dictCount)) {
if (dictCount[key] >= 2) {
result++;
}
}
return result;
}
console.log("result", countDuplicates(str)); // 2
// Write function that outputs the sorted concatenation of 2 sorted arrays.
// Example [1, 4, 9][2, 7, 11] => [1, 2, 4, 7, 9, 11]
function concatAndSort(arr1, arr2) {
let point_1 = 0;
let point_2 = 0;
const result = [];
console.log("arr1", arr1);
console.log("arr2", arr2);
while (point_1 < arr1.length || point_2 < arr2.length) {
if (point_1 === arr1.length) {
result.push(arr2[point_2]);
point_2++;
continue;
}
if (point_2 === arr2.length) {
result.push(arr1[point_1]);
point_1++;
continue;
}
if (arr1[point_1] < arr2[point_2]) {
result.push(arr1[point_1]);
point_1++;
continue;
} else {
result.push(arr2[point_2]);
point_2++;
continue;
}
}
return result;
}
console.log(concatAndSort([1, 4, 9], [2, 7, 11, 12]));