javascript - JS : Create a method to return an array that does not include the index values from the array passed to my method

标签 javascript arrays object methods filter

我正在尝试创建一个添加到 Array.prototype 对象的方法。目标是返回一个数组,该数组不包含传递给我的方法的数组中的索引值。

以下是我的测试规范。

describe('doNotInclude', () => {
  it('the doNotInclude method is added to the Array.prototype object', () => {
    expect(typeof Array.prototype.doNotInclude).toBe('function');
  });
  it('returns an array', () => {
    expect(Array.isArray([1, 2, 3, 4].doNotInclude(3))).toBe(true);
    expect(Array.isArray([1, 2, 3, 4].doNotInclude([0, 2]))).toBe(true);
  });
  it('does not include the index values from the array passed to `doNotInclude`', () => {
    expect([1, 2, 3, 4, 5].doNotInclude([3, 4])).toEqual([1, 2, 3]);
    expect(
      ['zero', 'one', 'two', 'three', 'four', 'five', 'six'].doNotInclude([
        0,
        1,
      ])
    ).toEqual(['two', 'three', 'four', 'five', 'six']);

我的代码如下:

Array.prototype.doNotInclude = function (arr){
    return this.filter((elem, index) => {
      if (!arr.includes(index)){
        return elem; 
      }
    })
  }

我的代码没有通过任何规范。我究竟做错了什么?

还要检查我的概念理解,过滤器方法在哪个数组上运行?它是包含索引的那个吗?

最佳答案

我假设您需要一个方法,该方法采用给定数组并删除与作为参数传递的数组值匹配的值。该演示将返回值与传入数组的值不匹配的数组索引。这可以通过最新的数组方法 .flatMap() 实现,它本质上是 .map( ).flat() 方法相结合。映射部分将对每个值运行一个函数,就像 .map() 所做的一样,但不同之处在于每个返回都是一个数组:

 array.map(function(x) { return x});
 array.flatMap(function(x) { return [x]});

如果你想删除一个值,你返回一个空数组:

  array.map(function(x) { return x}).filter(function(x) { return x !== z}); 
  array.flatMap(function(x) { return x !== z ? [x] : []}); 

通过使用三元控件,您可以直接删除值,而不是通过 .filter() 间接删除。

  if x does not equal z return [x] else return empty array []
    return x !== z ? [x] : []

然后将结果展平为普通数组。

Array.prototype.exclude = function(array) {
  return this.flatMap((value, index) => {
    return array.includes(value) ? [] : [index];
  })
}

let x = [1, 2, 3, 4, 5, 6, 7];

let z = x.exclude([3, 4]);

console.log(JSON.stringify(z));

关于javascript - JS : Create a method to return an array that does not include the index values from the array passed to my method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56433584/

相关文章:

原始变量更改后的javascript变量更改值

javascript - 我可以将值传递给同级组件而不将其保存为变量吗?

c++ - 如何使用相同的调用签名在张量中索引和分配元素?

javascript - 如何使用js过滤方法查找包含特定字符串的项目数

android - 确定 JSON 是 JSONObject 还是 JSONArray

java - 写一个类似Spring Bean实例化方法 context.getBean ("beanobjectname",Type)

javascript - 使用 svg 内的 javascript 函数操作 svg 外的对象

javascript - jQuery - 填充父行下方的子表

Array.SetValue 在运行时的 C# 类型转换

javascript - 无法干净地跳出 javascript 中的 for 循环