简单算法
传入字符串,返回不重复字符串的最长长度
function mostStringLen(str) {
let newStr = ''
for (let value of str) {
newStr.indexOf(value) === -1 && (newStr += value)
}
if (newStr) {
return newStr.length
}
return '当前没有长度'
}
console.log('不重复最长长度', mostStringLen('abaaa'));
传入下标,返回斐波那契数列下标对应的一项
function feibonace(index) {
let x = 0
let y = 1
let z = 0
if (index === 0) {
return 0
}
if (index === 1) {
return 1
}
for (let i = 0; i <= index - 2; i++) {
z = x + y
x = y
y = z
}
return z
}
console.log('feibonace', feibonace(9));
冒泡排序
let arr = [88, 123, 1, 33, 5, 89, 12, 7]
for (let i = 0; i < arr.length - 1; i++) {
for (let j = 0; j < arr.length - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
let temp = arr[j]
arr[j] = arr[j + 1]
arr[j + 1] = temp
}
}
}
console.log('换位', arr);
传入数组和目标值,返回和为目标值的两项的下标
let arr = [1, 4, 5, 9, 13]
let target = 13
function findArrIndex(arr1, target) {
let obj = {}
for (let i = 0; i < arr1.length; i++) {
if (obj[target - arr[i]] !== undefined) {
return [obj[target - arr[i]], i]
}
obj[arr[i]] = i
}
return []
}
console.log('findArrIndex(arr,13)', findArrIndex(arr, 13));
回文数
let strNum = 'abccba'
function reverse(strNum) {
num2 = strNum.toString().split('').reverse().join('')
if (strNum instanceof Number) {
num2 = Number(num2)
}
istrue = strNum === num2 ? true : false
return istrue
}
console.log(reverse(strNum));
数组去重reduce方法
let arr = ['a', 'b', 'a', 'c', 'b', 'c', 'a', 'v', 'r', 'a', 'v', 'r', 'r']
let result = arr.reduce((prev, cur, index) => {
prev.indexOf(cur) === -1 && prev.push(cur)
return prev
}, [])
console.log('result', result);
字符串去重
let str = 'ffweuhfiowefjopxkopscmaicnweiyfgygdidbasdjaonvwiebvuwigasndjasncjasbceuihuaed'
let str1 = ''
for (let i = 0; i < str.length; i++) {
(str1.indexOf(str[i]) === -1) && (str1 += str[i])
}
console.log('str1--->', str1);
reduce累加
let numArr = [2 , 4, 6, 9, 10, 13, 16]
let addNum = numArr.reduce((prev, cur, index) => {
return prev += cur
}, 0)
console.log('addNum', addNum);
数组扁平化
let arr = [1, 2, 3, [4, 5, 6, [1, 2, [100, 200]]], 7, 8, [[3, 6], 9, 10]]
const bianping = (arr) => {
let resArr = []
arr.forEach(item => {
resArr = resArr.concat(Array.isArray(item) ? bianping(item) : item)
})
return resArr
}
console.log('bianping(arr)', bianping(arr));
查找多级嵌套的数组
let arr = [
{
id: 1,
label: "上海",
children: [
{
id: 4,
label: "北京",
children: [
{
id: 10,
label: '深圳',
children: [
{
id: 11,
label: "苏州"
}
]
}
]
},
{
id: 5,
label: "西安",
},
],
},
{
id: 2,
label: "杭州"
}
]
const serch = ({ id, title }, arr) => {
let result = undefined
arr.forEach((item, index) => {
if (item.id === id) {
result = item
}
if (item.id !== id && result === undefined) {
if (item.hasOwnProperty('children')) {
const { children } = item
result = serch({ id, title }, children)
} else {
result = 'have no'
}
}
})
return result
}
console.log('serch', serch({ id: 4, title: '北京' }, arr));