前端面试题系列---3

题目一(重复数组元素)

用尽可能多的方法找出数组中重复出现过的元素
例如:[1,2,4,4,3,3,1,5,3] 输出:[1,3,4]

function duplicate(arr){
    arr.sort()
    let newArr = []
    for (let i = 0; i < arr.length; i++) {
         let str = arr[i]
         if (i !== arr.lastIndexOf(str) && newArr.indexOf(str) === -1){
             newArr.push(str)
         }
         i = arr.lastIndexOf(str)
     }
     return newArr
}

首先给arr数组排序,这样可以让相同的元素都连续排在一起,然后判断相同元素出现的第一个位置和最后一个位置值是否相等,若相等则说明该元素只出现了一次,若不相等则该元素肯定是重复的,push到新的数组中,然后把最后一个位置的值传给i继续循环数组里的下一个不同的元素。

题目二(查找某些词都存在哪个文档里)

给定一些文档(docs)、词(words),找出词在文档中全部存在的所有文档

let docs = [
    {
        id: 1,
        words: ['hello', 'world']
    },
    {
        id: 2,
        words: ['hello', 'kids']
    },
    {
        id: 3,
        words: ['zzzz', 'hello']
    },
    {
        id: 4,
        words: ['world', 'kids']
    }
]
this.findList(docs, ['hello'])
function findList (docs, words){
    var targetArr = []
    let arrStr = arr.join('?')
    for (let i = 0; i < docs.length; i++) {
        let wordsStr = docs[i].words.join('?')
        if (wordsStr.indexOf(arrStr) !== -1) {
            targetArr.push(docs[i])
        }
    }
    for (let i = 0; i < targetArr.length; i++) {
        console.log('文档' + targetArr[i].id)
    }
}

猜你喜欢

转载自blog.csdn.net/one_girl/article/details/80312842