Как консолидировать массив с количеством повторяющихся значений [duplicate]

Сторонние альтернативы SimpleHtmlDom, которые используют DOM вместо String Parsing: phpQuery , Zend_Dom , QueryPath и FluentDom .

53
задан ROMANIA_engineer 5 January 2016 в 16:43
поделиться

15 ответов

function count() {
    array_elements = ["a", "b", "c", "d", "e", "a", "b", "c", "f", "g", "h", "h", "h", "e", "a"];

    array_elements.sort();

    var current = null;
    var cnt = 0;
    for (var i = 0; i < array_elements.length; i++) {
        if (array_elements[i] != current) {
            if (cnt > 0) {
                document.write(current + ' comes --> ' + cnt + ' times<br>');
            }
            current = array_elements[i];
            cnt = 1;
        } else {
            cnt++;
        }
    }
    if (cnt > 0) {
        document.write(current + ' comes --> ' + cnt + ' times');
    }

}

Демо-скрипт

14
ответ дан Vinay Pratap Singh 25 August 2018 в 13:26
поделиться

Используя array.map, мы можем уменьшить цикл, см. это в jsfiddle

function Check(){
    var arr = Array.prototype.slice.call(arguments);
    var result = [];
    for(i=0; i< arr.length; i++){
        var duplicate = 0;
        var val = arr[i];
        arr.map(function(x){
            if(val === x) duplicate++;
        })
        result.push(duplicate>= 2);
    }
    return result;
}

To Test:

var test = new Check(1,2,1,4,1);
console.log(test);
0
ответ дан Ali Adravi 25 August 2018 в 13:26
поделиться

Дублирует в массиве, содержащем алфавиты:

var arr = ["a", "b", "a", "z", "e", "a", "b", "f", "d", "f"],
  sortedArr = [],
  count = 1;

sortedArr = arr.sort();

for (var i = 0; i < sortedArr.length; i = i + count) {
  count = 1;
  for (var j = i + 1; j < sortedArr.length; j++) {
    if (sortedArr[i] === sortedArr[j])
      count++;
  }
  document.write(sortedArr[i] + " = " + count + "<br>");
}

Дублирует в массиве, содержащем числа:

var arr = [2, 1, 3, 2, 8, 9, 1, 3, 1, 1, 1, 2, 24, 25, 67, 10, 54, 2, 1, 9, 8, 1],
  sortedArr = [],
  count = 1;
sortedArr = arr.sort(function(a, b) {
  return a - b
});
for (var i = 0; i < sortedArr.length; i = i + count) {
  count = 1;
  for (var j = i + 1; j < sortedArr.length; j++) {
    if (sortedArr[i] === sortedArr[j])
      count++;
  }
  document.write(sortedArr[i] + " = " + count + "<br>");
}

0
ответ дан Ankit Gupta 25 August 2018 в 13:26
поделиться

Одиночная линия на основе функции уменьшения массива

const uniqueCount =  ["a", "b", "c", "d", "d", "e", "a", "b", "c", "f", "g", "h", "h", "h", "e", "a"];
const distribution = uniqueCount.reduce((acum,cur) => Object.assign(acum,{[cur]: (acum[cur] | 0)+1}),{});
console.log(JSON.stringify(distribution,null,2));

4
ответ дан dinigo 25 August 2018 в 13:26
поделиться

Я думаю, что это самый простой способ подсчета вхождений с одинаковым значением в массиве.

var a = [true, false, false, false];
a.filter(function(value){
    return value === false;
}).length                                      
2
ответ дан Dmytro Kozlovskyi 25 August 2018 в 13:26
поделиться
var uniqueCount = ['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a'];
// here we will collect only unique items from the array
var uniqueChars = [];

// iterate through each item of uniqueCount
for (i of uniqueCount) {
// if this is an item that was not earlier in uniqueCount, 
// put it into the uniqueChars array
  if (uniqueChars.indexOf(i) == -1) {
    uniqueChars.push(i);
  } 
}
// after iterating through all uniqueCount take each item in uniqueChars
// and compare it with each item in uniqueCount. If this uniqueChars item 
// corresponds to an item in uniqueCount, increase letterAccumulator by one.
for (x of uniqueChars) {
  let letterAccumulator = 0;
  for (i of uniqueCount) {
    if (i == x) {letterAccumulator++;}
  }
  console.log(`${x} = ${letterAccumulator}`);
}
1
ответ дан Ilya Kushlianski 25 August 2018 в 13:26
поделиться

Что-то вроде этого:

    uniqueCount = ["a","b","c","d","d","e","a","b","c","f","g","h","h","h","e","a"];
    var  count = {};
    uniqueCount.forEach(function(i) { count[i] = (count[i]||0) + 1;});
    console.log(count);

Используйте простой цикл for вместо forEach, если вы не хотите, чтобы это сломалось раньше браузеры.

37
ответ дан Isak La Fleur 25 August 2018 в 13:26
поделиться

Я наткнулся на этот (очень старый) вопрос. Интересно, что самое очевидное и изящное решение (imho) отсутствует: Array.prototype.reduce (...) . Все основные браузеры поддерживают эту функцию с 2011 года (IE) или даже раньше (все остальные):

var arr = ['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a'];
var map = arr.reduce(function(prev, cur) {
  prev[cur] = (prev[cur] || 0) + 1;
  return prev;
}, {});

// map is an associative array mapping the elements to their frequency:
document.write(JSON.stringify(map));
// prints {"a": 3, "b": 2, "c": 2, "d": 2, "e": 2, "f": 1, "g": 1, "h": 3}

17
ответ дан isnot2bad 25 August 2018 в 13:26
поделиться

У вас может быть объект, содержащий счетчики. Пройдите по списку и увеличьте количество для каждого элемента:

var counts = {};

uniqueCount.forEach(function(element) {
  counts[element] = (counts[element] || 0) + 1;
});

for (var element in counts) {
  console.log(element + ' = ' + counts[element]);
} 
3
ответ дан John Keyes 25 August 2018 в 13:26
поделиться

Вы можете решить эту проблему без использования каких-либо циклов / while для ooo forEach.

function myCounter(inputWords) {        
    return inputWords.reduce( (countWords, word) => {
        countWords[word] = ++countWords[word] || 1;
        return countWords;
    }, {});
}

Надеюсь, это поможет вам!

4
ответ дан Pablo Souza 25 August 2018 в 13:26
поделиться
public class CalculateCount {
public static void main(String[] args) {
    int a[] = {1,2,1,1,5,4,3,2,2,1,4,4,5,3,4,5,4};
    Arrays.sort(a);
    int count=1;
    int i;
    for(i=0;i<a.length-1;i++){
        if(a[i]!=a[i+1]){
            System.out.println("The Number "+a[i]+" appears "+count+" times");
            count=1;                
        }
        else{
            count++;
        }
    }
    System.out.println("The Number "+a[i]+" appears "+count+" times");

}   

}

0
ответ дан Parv Johari 25 August 2018 в 13:26
поделиться

Вы можете сделать что-то вроде этого:

uniqueCount = ['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a'];
var map = new Object();

for(var i = 0; i < uniqueCount.length; i++) {
 if(map[uniqueCount[i]] != null) {
    map[uniqueCount[i]] += 1;
} else {
    map[uniqueCount[i]] = 1;
    }
}

теперь у вас есть карта со всеми значениями символов

3
ответ дан Rami 25 August 2018 в 13:26
поделиться

var string = ['a','a','b','c','c','c','c','c','a','a','a'];

function stringCompress(string){

var obj = {},str = "";
string.forEach(function(i) { 
  obj[i] = (obj[i]||0) + 1;
});

for(var key in obj){
  str += (key+obj[key]);
}
  console.log(obj);
  console.log(str);
}stringCompress(string)

/*
Always open to improvement ,please share 
*/

0
ответ дан sg28 25 August 2018 в 13:26
поделиться
var counts = {};
your_array.forEach(function(x) { counts[x] = (counts[x] || 0)+1; });
167
ответ дан SheetJS 25 August 2018 в 13:26
поделиться

Комбинация хороших ответов:

var count = {};
var arr = ['a', 'b', 'c', 'd', 'd', 'e', 'a', 'b', 'c', 'f', 'g', 'h', 'h', 'h', 'e', 'a'];
var iterator = function (element) {
    count[element] = (count[element] || 0) + 1;
}

if (arr.forEach) {
    arr.forEach(function (element) {
        iterator(element);
    });
} else {
    for (var i = 0; i < arr.length; i++) {
        iterator(arr[i]);
    }
}  

Надеюсь, что это полезно.

0
ответ дан Xiaodan Mao 25 August 2018 в 13:26
поделиться
Другие вопросы по тегам:

Похожие вопросы: