Count the Number of Times a Same Value Appears in a JavaScript Array

Count the number of times a same value appears in a javascript array

There might be different approaches for such purpose.
And your approach with for loop is obviously not misplaced(except that it looks redundantly by amount of code).
Here is some additional approaches to get the occurrence of a certain value in array:

  • Using Array.forEach method:

    var arr = [2, 3, 1, 3, 4, 5, 3, 1];

    function getOccurrence(array, value) {
    var count = 0;
    array.forEach((v) => (v === value && count++));
    return count;
    }

    console.log(getOccurrence(arr, 1)); // 2
    console.log(getOccurrence(arr, 3)); // 3
  • Using Array.filter method:

    function getOccurrence(array, value) {
    return array.filter((v) => (v === value)).length;
    }

    console.log(getOccurrence(arr, 1)); // 2
    console.log(getOccurrence(arr, 3)); // 3

Finding out how many times an array element appears

  • Keep a variable for the total count
  • Loop through the array and check if current value is the same as the one you're looking for, if it is, increment the total count by one
  • After the loop, total count contains the number of times the number you were looking for is in the array

Show your code and we can help you figure out where it went wrong

Here's a simple implementation (since you don't have the code that didn't work)

var list = [2, 1, 4, 2, 1, 1, 4, 5];  

function countInArray(array, what) {
var count = 0;
for (var i = 0; i < array.length; i++) {
if (array[i] === what) {
count++;
}
}
return count;
}

countInArray(list, 2); // returns 2
countInArray(list, 1); // returns 3

countInArray could also have been implemented as

function countInArray(array, what) {
return array.filter(item => item == what).length;
}

More elegant, but maybe not as performant since it has to create a new array.

How to find the number of repetitions of an item in an array in JavaScript?

Try this solution

 function getOccurrence(myArray, value) {
var count = 0;
myArray .forEach((val) => (val === value && count++));
return count;
}

Counting number of times value appears in an array using .forEach()

Your solution was almost correct:

const betterWords = "Hello World! This is a nice text. Awesome!"
let sentences = 0;
betterWords.split('').forEach(word => {
if (word === '.' || word === '!') {
return sentences += 1
}
});
console.log(sentences)

JavaScript count the number of times a specific value is mentioned in an array of objects

Using an object is more useful than an array here to save the data. But you can convert if need be.

json_output = [
{
"id": "1",
"Device Name": "device3",
"Software Name": "windows"
},
{
"id": "2",
"Device Name": "device6",
"Software Name": "windows"
},
{
"id": "3",
"Device Name": "device11",
"Software Name": "windows"
},
{
"id": "4",
"Device Name": "device11",
"Software Name": "windows_11"
},
{
"id": "5",
"Device Name": "device11",
"Software Name": "linux_sys"
}
];

new_obj = {};

for (obj of json_output) {
let key = obj["Software Name"];
new_obj[key] = json_output.filter(a => a["Software Name"] == key).length;
}

console.log( new_obj );

// do you need to format this as an array? if so, do this

const new_arr = [];
for (const [softwareName, count] of Object.entries(new_obj)) {
let row = {[softwareName]: count};
new_arr.push(row);
}

console.log( new_arr );

How to count certain elements in array?

Very simple:

var count = 0;
for(var i = 0; i < array.length; ++i){
if(array[i] == 2)
count++;
}

how many times a value is repeated in an array of objects

const employees = [
{ age: 35, name: 'David', position: 'Front-End' },
{ age: 24, name: 'Patrick', position: 'Back-End' },
{ age: 22, name: 'Jonathan', position: 'Front-End' },
{ age: 32, name: 'Raphael', position: 'Full-Stack' },
{ age: 44, name: 'Cole', position: 'Back-End' },
{ age: 28, name: 'Michael', position: 'Front-End' }
];

const obj = employees.reduce((val, cur) => {
val[cur.position] = val[cur.position] ? val[cur.position] + 1 : 1;
return val;
}, {});

const res = Object.keys(obj).map((key) => ({
position: key,
count: obj[key]
}));

console.log(res);


Related Topics



Leave a reply



Submit