1.反转字符串
a = '1312qwsadqwe'
console.log(a.split().reverse().join(','))
console.log(a.split().reduceRight((prev,curr)=>prev + curr))
2.解题很妙。
var arr = [1, 1, '1', 17, true, true, false, 'true', 'a', 'a']
var sets = new Set(arr)
var objs = new Map()
for (let i of sets) {
objs.set(i, arr.filter(n => i === n).length)
}
console.log(objs)
//{ H: 1, e: 1, l: 3, o: 2, W: 1, r: 1, d: 1 }
这里是比较简单的一道面试题
let str = 'Hello World'
let arr = str.split('')
let arr2 = arr.filter((item, index) => {
return item !== ' '
})
function countOccurrences(arr) {
const counts = {}; // 创建一个空对象来存储每个元素的计数
// 遍历数组
arr.forEach(elem => {
// 如果对象中已经存在当前元素,则递增计数;否则,将计数设置为1
// counts[elem] = (counts[elem] || 0) + 1; //看不懂
counts[elem] ? counts[elem]++ : counts[elem] = 1;
});
return counts;
}
const result = countOccurrences(arr2);
console.log(result)
3.
function twoSum(nums, target) {
const numMap = {};
for (let i = 0; i < nums.length; i++) {
const complement = target - nums[i];
if (numMap.hasOwnProperty(complement)) {
return [numMap[complement], i];
}
numMap[nums[i]] = i;
}
return [];
}
// 示例用法
console.log(twoSum([2, 7, 11, 15], 9)); // 输出: [0, 1]
console.log(twoSum([3, 2, 4], 6)); // 输出: [1, 2]
console.log(twoSum([3, 3], 6)); // 输出: [0, 1]
5.合并二维有序数组成一维有序数组,归并排序的思路
/**
* 解题思路:
* 双指针 从头到尾比较 两个数组的第一个值,根据值的大小依次插入到新的数组中
* 空间复杂度:O(m + n)
* 时间复杂度:O(m + n)
* @param {Array} arr1
* @param {Array} arr2
*/
function merge(arr1, arr2) {
var result = [];
while (arr1.length > 0 && arr2.length > 0) {
if (arr1[0] < arr2[0]) {
/*shift()方法用于把数组的第一个元素从其中删除,并返回第一个元素的值。*/
result.push(arr1.shift());
} else {
result.push(arr2.shift());
}
}
return result.concat(arr1).concat(arr2);
}
function mergeSort(arr) {
let lengthArr = arr.length;
if (lengthArr === 0) {
return [];
}
while (arr.length > 1) {
let arrayItem1 = arr.shift();
let arrayItem2 = arr.shift();
let mergeArr = merge(arrayItem1, arrayItem2);
arr.push(mergeArr);
}
return arr[0];
}
let arr1 = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[1, 2, 3],
[4, 5, 6],
];
let arr2 = [
[1, 4, 6],
[7, 8, 10],
[2, 6, 9],
[3, 7, 13],
[1, 5, 12],
];
console.log(mergeSort(arr1), "arr1");
console.log(mergeSort(arr2), "arr2");
function flattenArray(arr) {
return arr.reduce((acc, curr) => [...acc, ...curr]).sort((a, b) => a - b);
}
function flattenArray(arr) {
return arr.reduce((acc, curr) => acc.concat(curr)).sort((a, b) => a - b);
}
// 示例数据
const twoDimArray = [
[1, 2, 3],
[4, 5],
[6, 0, 22, 23],
];
const oneDimArray = flattenArray(twoDimArray);
console.log(oneDimArray);
6.计算数组的最高峰值 Math.max 这里的Math.max接收的是字符串
const findPeaks = (mountain) => {
const res = []
mountain.forEach((e, i) => {
if (mountain[i] > mountain[i - 1] && mountain[i] > mountain[i + 1]) {
res.push(mountain[i])
}
})
return Math.max(...res);
}
findPeaks([1, 2, 1, 3, 1, 4, 2, 6, 7, 8, 9, 3, 0])