javascript 给定一个字符串数组,编写一个函数,返回一个对象数组,表示每个唯一字符串及其在原始数组中的频率

q5lcpyga  于 2023-03-11  发布在  Java
关注(0)|答案(3)|浏览(164)

我想打印字符串和它的频率作为一个对象存储在一个数组中。我一直只使用reduce方法这样做,并希望通过相同的方法只的结果,谁能告诉我,我应该纠正以下代码:

const strings = ["pink", "red", "pink", "yellow", "yellow", "yellow"];

const frequencyOfStrings = (arrayOfStrings) => {
  return arrayOfStrings.reduce((acc, curr) => {
    if (acc[curr]) {
      acc[curr]++;
    } else {
      acc[curr] = 1;
    }
    return acc;
  }, []);
};

console.log(frequencyOfStrings(strings));

我得到的输出为:

[ pink: 2, red: 1, yellow: 3 ]

而我希望输出为:

[{ string: 'pink', frequency: 2 }, { string: 'red', frequency: 1 }, { string: 'yellow', frequency: 3 }]

到目前为止,我是一个Javascript的初学者,对时间复杂性一无所知。

ohfgkhjo

ohfgkhjo1#

要实现所需的输出格式,需要修改reduce函数,使其返回对象数组而不是对象。

const strings = ["pink", "red", "pink", "yellow", "yellow", "yellow"];

const frequencyOfStrings = (arrayOfStrings) => {
  return Object.entries(
    arrayOfStrings.reduce((acc, curr) => {
      if (acc[curr]) {
        acc[curr]++;
      } else {
        acc[curr] = 1;
      }
      return acc;
    }, {})
  ).map(([string, frequency]) => ({ string, frequency }));
};

console.log(frequencyOfStrings(strings));
h79rfbju

h79rfbju2#

最好使用foreach来完成这项工作,但是您可以使用reduce,但需要更改它内部的逻辑。
在您想要的输出中,您需要objectsarray,因此在您的reduce中,您需要在您的输出array中查找正确的object,然后更新它的frequency,如果它与您的current元素匹配,否则添加一个新的1元素作为frequency
这是应该如何是你的代码:

const frequencyOfStrings = (arrayOfStrings) => {
  return arrayOfStrings.reduce((acc, curr) => {
    let foundIndex = acc.findIndex(el => el["string"] === curr);
    if (foundIndex >= 0) {
      acc[foundIndex].frequency++;
    } else {
      acc.push({
        "string": curr,
        "frequency": 1
      })
    }
    return acc;
  }, []);
};

演示:

const strings = ["pink", "red", "pink", "yellow", "yellow", "yellow"];

const frequencyOfStrings = (arrayOfStrings) => {
  return arrayOfStrings.reduce((acc, curr) => {
    let foundIndex = acc.findIndex(el => el["string"] === curr);
    if (foundIndex >= 0) {
      acc[foundIndex].frequency++;
    } else {
      acc.push({
        "string": curr,
        "frequency": 1
      })
    }
    return acc;
  }, []);
};

console.log(frequencyOfStrings(strings));
g6baxovj

g6baxovj3#

为什么你坚持使用一个明显不适合这个工作的工具(reduce)呢?只要使用一个循环:

const frequencyOfStrings = (arrayOfStrings) => {
    let m = new Map

    for (let string of arrayOfStrings)
        if (m.has(string))
            m.get(string).frequency += 1
        else
            m.set(string, {string, frequency: 1})

    return [...m.values()]
}

相关问题