2

I have pushed a random amount of strings into an array.

var array = ["car", "plane", "plane", "car", "car"];

Id like to retrieve the Arrays values and get the amount of times they were pushed into the Array. i.E

var a = "car";
var aCount = 3;
var b = "plane";
var bCount = 2;

var text = "'" + a + "'" + " was found " + aCount + " times";
return text

I dont see how i can use a loop to compare array[i] with all the other values of the array, especially considerung array.length is randomly determined ?

thank you

4 Answers4

2

Create an object with the keys set as the array values and start counting!

var arrayMap = {};
for (var i = 0; i < array.length; i++) {
    if (arrayMap.hasOwnProperty(array[i])) {
        arrayMap[array[i]]++;
    } else {
        arrayMap[array[i]] = 1;
    }
}

arrayMap will now have a count of all your array values.

Demo: http://jsfiddle.net/oe0x6dbg/

tymeJV
  • 103,943
  • 14
  • 161
  • 157
1

You can Array.reduce:

var array = ["car", "plane", "plane", "car", "car"];

var result = array.reduce(function(dict, item) {
                 dict[item] = (dict[item] || 0) + 1;
                 return dict;
             }, {});

for(var prop in result) {
    console.log('\'' + prop + '\' was found ' + result[prop] + ' times');
}

/*
    result = {
        'car': 3,
        'plane': 2
    }

    Console:
    --------
    'car' was found 3 times
    'plane' was found 2 times
*/
manji
  • 47,442
  • 5
  • 96
  • 103
0

You can do this

var arrStr = array.join();
var result = {};
for (var i = 0; i < array.length; i++) {
    result[array[i]] = arrStr.match(new RegExp(array[i], "g")).length;
    arrStr.replace(new RegExp(array[i], "g"), "");
}
console.log(result); // {car: 3, plane: 2}
Amit Joki
  • 58,320
  • 7
  • 77
  • 95
0

A simple solution could be to add a "count" object like so:

var array = ["car", "plane", "plane", "car", "car"];

var count = {};

// Map each element in the array to a key in the object
for (var i = 0; i < array.length; i++) {
    if (typeof count[array[i]] === 'undefined') {
        count[array[i]] = 1;
    } else {
        count[array[i]]++;
    }
}

// Loop through the object and print out the counts
for (var i in count) {
    console.log("'" + i + "'" + " was found " + count[i] + " times");
}

JSFiddle

neelsg
  • 4,802
  • 5
  • 34
  • 58