Ramda 之 without()

栏目: JavaScript · 发布时间: 6年前

内容简介:若要找出第一個 Array 不在第二個 Array 的 Element,我們會使用VS Code 1.33.1Quokka 1.0.209

若要找出第一個 Array 不在第二個 Array 的 Element,我們會使用 difference() ,若要找出第二個 Array 不在第一個 Array 的 Element 呢 ?

Version

VS Code 1.33.1

Quokka 1.0.209

Ramda 0.26.1

Functional

import { flip, difference } from 'ramda';

let first = [1, 3, 5, 7];
let second = [1, 4, 7];

let without = flip(difference);
console.log(without(first, second));

想知道 second array 哪些 element 不存在於 first array,,若不知道 Ramda 提供了 without() ,其實也可以由 difference()flip() 組合出來。

Ramda 之 without()

without()

Value

import { without } from 'ramda';

let first = [1, 3, 5, 7];
let second = [1, 4, 7];

console.log(without(first, second));

其實 Ramda 已經提供了 without() ,可直接使用。

without()

[a] → [a] → [a]

回傳第二個 array 不存在於第一個 array 部分

Ramda 之 without()

Object

import { without } from 'ramda';

let first = [
  { firstName: 'Kevin', lastName: 'Yang'},
];

let second = [
  { firstName: 'Sam',   lastName: 'Xiao'},
  { firstName: 'Kevin', lastName: 'Yang'},
  { firstName: 'Jimmy', lastName: 'Huang'},
]

console.dir(without(first, second));

second array 的 element 為 object,想得知不存在於 first array 的 object 有哪些, without() 依然適用。

ECMAScript 的 === ,對於 object 是 reference equality,但以處理 data 角度而言,這並沒有實質用處,而 without() 比較的是 value equality,也就是 property 相等,就視為兩個 object 相等,這在實務上非常有用

Ramda 之 without()

Conclusion

  • Ramda 並沒有如同 differenceWith() 提供 withoutWith() ,但也可組合 flip()differenceWith() 成為 withoutWith()
  • without() 可輕易找出兩個 array 不重複部分,尤其對於 object 是比較其 value equality,而不是 reference equality,非常實用

Reference

Ramda , without()

Ramda , difference()

Ramda , flip()


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

JavaScript Patterns

JavaScript Patterns

Stoyan Stefanov / O'Reilly Media, Inc. / 2010-09-21 / USD 29.99

What's the best approach for developing an application with JavaScript? This book helps you answer that question with numerous JavaScript coding patterns and best practices. If you're an experienced d......一起来看看 《JavaScript Patterns》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

html转js在线工具
html转js在线工具

html转js在线工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具