最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - For a given array of string, each with an item name, group all the string by item name - Stack Overflow

programmeradmin4浏览0评论

str_arr= ["a", "a", "b", "c", "b"]

The resulting array should be ["a 2", "b 2", "c 1"].

I can't get the desired result with the following code.

function foo(str) {
    var a = [], b = [], prev;

    for ( var i = 0; i < str.length; i++ ) {
        if ( str[i] !== prev ) {
            a.push(str[i]);
            b.push(1);
        } else {
            b[b.length-1]++;
        }
        prev = arr[i];
    }

    return [a, b];
}

var result = foo(str_arr);
var newA = result[0].map((e, i) => e  + " " + result[1][i]+ "<br>");

str_arr= ["a", "a", "b", "c", "b"]

The resulting array should be ["a 2", "b 2", "c 1"].

I can't get the desired result with the following code.

function foo(str) {
    var a = [], b = [], prev;

    for ( var i = 0; i < str.length; i++ ) {
        if ( str[i] !== prev ) {
            a.push(str[i]);
            b.push(1);
        } else {
            b[b.length-1]++;
        }
        prev = arr[i];
    }

    return [a, b];
}

var result = foo(str_arr);
var newA = result[0].map((e, i) => e  + " " + result[1][i]+ "<br>");
Share Improve this question edited Dec 21, 2019 at 20:07 ErrorByNight asked Dec 21, 2019 at 19:25 ErrorByNightErrorByNight 792 silver badges7 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 4

You could take an object for counting the items and

  • get the keys of the object,
  • sort by count descending and by key ascending,
  • map key and count as string.

Then return the array.

function foo(transactions) {
    var counts = {};

    for (var i = 0; i < transactions.length; i++) {
        counts[transactions[i]] = (counts[transactions[i]] || 0) + 1;
    }

    return Object
        .keys(counts)
        .sort((a, b) => counts[b] - counts[a] || a > b || -(a < b))
        .map(k => k + ' ' + counts[k]);
}

var transactions = ["notebook", "notebook", "mouse", "keyboard", "mouse"],
    result = foo(transactions);

console.log(result);

No sort required. Original array unaffected.

function group(arr) {
  var hits = {}, group_arr = [];
  for (var i = 0; i < arr.length; i++) hits[arr[i]] = (hits[arr[i]] || 0) + 1;
  for (var hit in hits) Object.prototype.hasOwnProperty.call(hits, hit) && group_arr.push(hit + " " + hits[hit]);
  return group_arr;
}

console.log(group(["a", "a", "b", "c", "b"]));

Here's a function to add counts to the unique words in the array.

This one does it more old-school, by iterating over the sorted array.

function countDistinctWords (arr) {
  if (arr.length === 0) return arr;
  arr = arr.sort();
  let result = [];
  let n = 1;
  for (let i = 1; i < arr.length; i++) { 
    if (arr[i-1] == arr[i]) {n++}
    if (arr[i-1] !== arr[i]) {
      result.push(arr[i-1]+' '+n);
      n=1;
    }
  }
  result.push(arr[arr.length-1]+' '+n);
  return result;
}

str_arr= ["a", "a", "b", "c", "b"];

var str_arr2 = countDistinctWords(str_arr);
console.log(str_arr2);

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论