0

我在Javascript. 我尽力解决,但我错过了一些边缘情况。我需要有关解决方案的帮助。

以下是我执行的步骤。我仍然是学习数据结构和算法的初学者。我不确定以下方法是否可行。我需要帮助来解决这个问题。谢谢

问题

类型数组排序您的任务是编写一个函数,该函数接受一个包含不同类型值的数组并返回一个对象,该对象列出了在各个子部分中分组的所有不同类型。

Examples
Types   Input   Output
Primitive types [ 1, "string", 2, true, false ] { number: [ 1, 2 ], string: [ "string" ], boolean: [ true, false ] }
Differrent Object Types [ {}, [], null ]    { object: [ {} ], array: [ [] ], null: [ null ] }

不需要考虑边缘案例类实例,可以将其视为此分配的类型对象。

const filterArray = () => {
  // fill me with code
}

export default filterArray


测试

import filterArray from './solution'

describe('basic tests', () => {
  test('strings', () => {
    expect(filterArray(["a", "b", "c"])).toEqual({ string: ["a", "b", "c"] })
  })
})```

我解决这个问题的思考过程

1.create new array that will be returned..
2.loop over given array...
3.check type if no: append "number: [1, 2]"
4.add more if else conditions for other types
4

2 回答 2

0

您可以使用Array.prototype.reduce(). 确保你理解下面的代码;不要简单地复制和粘贴它。

const func1 = () => {};
const func2 = () => {};

const input = [1, 2, 3.75, 'a', 'b', 'c', {}, { foo: 'bar' }, [], ['foo', 'bar'], null, null, undefined, null, true, false, func1, func2, NaN, NaN, 5 / 0, 0 / 5];

const output = input.reduce((outObj, item) => {
  // check the type of the item
  let itemType = typeof item;

  // if the item is of type 'number' you might want to discriminate
  // between actual numbers and `NaN` (Not-a-Number)
  if (itemType === 'number' && isNaN(item)) itemType = 'nan';
  
  // if the item is of type 'object' you will have to further check
  // whether it is `null`, an array, or an actual object
  if (itemType === 'object') {
    if (item === null) itemType = 'null';
    if (Array.isArray(item)) itemType = 'array';
  }
  
  // if the output object already contains a key for the item type
  // add the item to that key otherwise
  // create the output object new type key and add the item to it
  outObj[itemType] = outObj[itemType] ? [...outObj[itemType], item] : [item];
  
  // return the output object
  return outObj;
}, {});

// test
console.log(output)

于 2022-03-04T16:45:51.087 回答
0
const filterArray = (arr) => {
  let result = {}

  let str;
  // other variables
  for (const it of arr) {
    switch (typeof it) {
      case "string":
        if (!str) {
          str = []
          result.string = str
        }
        str.push(it)
        break;
      // other cases
    }
  }
  return result
}
于 2022-03-04T16:44:47.540 回答