每日打卡(四):lodash.js => _.fromPairs + _.indexOf + _.intersection

100 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第四天,点击查看活动详情

_.fromPairs(pairs)

概念

_.toPairs正好相反;这个方法返回一个由键值对pairs构成的对象。

参数

  1. pairs  (Array) : 键值对pairs

返回值

(Object) : 返回一个新对象。

例子

_.fromPairs([['fred', 30], ['barney', 40]]);
// => { 'fred': 30, 'barney': 40 }

手写实现

function myFrompairs(arrs) {
    let res = {}
    if (arrs == null) return res  // 如果arrs为空 返回{} 
        arrs.map((item) => { // 遍历arrs 
            res[item[0]] = item[1] // 形成键值对
        })
    return res
}

核心是遍历和键值对的形成

_.indexOf(array, value, [fromIndex=0])

概念

使用SameValueZero 等值比较,返回首次 value 在数组array中被找到的 索引值, 如果 fromIndex 为负值,将从数组array尾端索引进行匹配。

参数

  1. array  (Array) : 需要查找的数组。
  2. value  ()* : 需要查找的值。
  3. [fromIndex=0]  (number) : 开始查询的位置。

返回值

(number) : 返回 值value在数组中的索引位置, 没有找到为返回-1

例子

_.indexOf([1, 2, 1, 2], 2);
// => 1
 
// Search from the `fromIndex`.
_.indexOf([1, 2, 1, 2], 2, 2);
// => 3

手写实现

function myIndexOf(arr, tar, start) {
    if (Array.isArray(arr) === true && arr.length === 0) return // 数组不为空
    let res
    if (start == undefined) return res = arr.indexOf(tar) // 未传入起始位置 indexOf 默认索引
    return res = arr.indexOf(tar, start) // 返回索引结果
}

核心是数组indexOf方法

_.intersection([arrays])

概念

创建唯一值的数组,这个数组包含所有给定数组都包含的元素,使用SameValueZero进行相等性比较。(注:可以理解为给定数组的交集)

参数

  1. [arrays]  (...Array) : 待检查的数组。

返回值

(Array) : 返回一个包含所有传入数组交集元素的新数组。

例子

_.intersection([2, 1], [4, 2], [1, 2]);
// => [2]

手写实现

function myIntersection(...arrs) {
    if (Array.isArray(arrs) === true && arrs.length === 0) return // 数组不为空
    let res = []
    arrs.map(item => {  // map 遍历
        if (!res.length){ 
            res.push(...new Set(item)) // res没有长度时 先筛选出一组
        } else {
            let arr = new Set(item)
            res = res.filter( i => arr.has(i)) // 筛选最终结果
        }
    })
    return res
}

核心是第一次筛选和数组filter() 和 has()方法的使用