Given an array of strings, write a function that returns an array of objects representing each unique string and its frequency in the original array

huangapple go评论55阅读模式
英文:

Given an array of strings, write a function that returns an array of objects representing each unique string and its frequency in the original array

问题

以下是您要的代码部分的翻译:

我想要打印字符串及其频率作为存储在数组内的对象我一直在使用 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 的初学者对时间复杂性一无所知就目前而言
英文:

I want to print the string and the frequency of it as an object stored inside an array. I have been using only reduce method to do so and want result through the same method only, Can anyone tell me what should I rectify in the below code:

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));

I am getting output as:

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

Whereas I want my output as:

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

P.S - I am a beginner at Javascript with no knowledge of time-complexities, as of now.

答案1

得分: 2

为了实现所需的输出格式,您需要修改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));

请注意,我已经移除了HTML代码标记,只返回了JavaScript代码的翻译部分。

英文:

To achieve the desired output format, you need to modify the reduce function to return an array of objects instead of an object.
Here is the updated code

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const strings = [&quot;pink&quot;, &quot;red&quot;, &quot;pink&quot;, &quot;yellow&quot;, &quot;yellow&quot;, &quot;yellow&quot;];

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

console.log(frequencyOfStrings(strings));

<!-- end snippet -->

答案2

得分: 1

以下是翻译好的部分:

// 最好使用 `foreach` 来执行这个任务,但你也可以使用 `reduce`,需要在其中更改逻辑。

在你所期望的输出中你想要一个包含 `objects`  `array`所以在你的 `reduce` 你需要查找输出 `array` 中的正确 `object`然后更新它的 `frequency`如果它与你的 `current` 元素匹配否则添加一个新的元素 `frequency`  `1`

以下是你的代码应该是这样的

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));
英文:

It's better to use a foreach to do the job, but you can use reduce and you need to change the logic inside it.

In your desired output you want an array of objects, so inside your reduce, you need to look for the right object in your output array then update its frequency, if it matches your current element, otherwise add a new element with 1 as frequency.

This is how should be your code:

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

Demo:

<!-- begin snippet: js hide: true console: true babel: false -->

<!-- language: lang-js -->

const strings = [&quot;pink&quot;, &quot;red&quot;, &quot;pink&quot;, &quot;yellow&quot;, &quot;yellow&quot;, &quot;yellow&quot;];

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

console.log(frequencyOfStrings(strings));

<!-- end snippet -->

答案3

得分: 0

为什么坚持使用明显不适合的工具 (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()]
}
英文:

Why do you insist on using a tool (reduce) which is obviously not appropriate for the job? Just use a loop:

const frequencyOfStrings = (arrayOfStrings) =&gt; {
    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()]
}

huangapple
  • 本文由 发表于 2023年3月9日 15:39:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/75681649.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定