Web Analytics Made Easy -
StatCounter Manipulating array of object in Javascript - CodingForum

Announcement

Collapse
No announcement yet.

Manipulating array of object in Javascript

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • Manipulating array of object in Javascript

    Hi, Need help in manipulating array of objects in Javascript. I'm intermediate in JS programming and finding tricke to manipulate the array of object
    For ex
    Obj ={
    Peter : {'apple', 'orange', 'grapes', 'banana'}
    George : ['apple', 'strawberry', 'kiwi', 'blueberry']
    John : ['apple', 'banana']
    },


    So I need to find the most like fruit in the array of objects?

  • #2
    I assume this should be an array too?
    Code:
    Peter : {'apple', 'orange', 'grapes', 'banana'}
    If so, this should do the job:
    Code:
                var obj = {
                    Peter: ['apple', 'orange', 'grapes', 'banana'],
                    George: ['apple', 'strawberry', 'kiwi', 'blueberry'],
                    John: ['apple', 'banana']
                };
                var fruits = {};
                for (var key in obj) {
                    for (var i = 0; i < obj[key].length; i++) {
                        var fruit = obj[key][i];
                        if (!fruits[fruit]) fruits[fruit] = 0;
                        fruits[fruit]++;
                    }
                }
                arrfruits = [];
                for (var key in fruits) arrfruits.push([key, fruits[key]]);
                arrfruits.sort(function(a, b) {return b[1] - a[1]});
                console.log(arrfruits[0]);
    I'm curious if there's a simpler solution.
    Last edited by Sempervivum; Sep 20, 2016, 08:05 AM.

    Comment


    • #3
      Need help in manipulating array of objects in Javascript.
      you don't have an array of objects there. that's an object containing arrays.
      The computer is always right. The computer is always right. The computer is always right. Take it from someone who has programmed for over ten years: not once has the computational mechanism of the machine malfunctioned.
      André Behrens, NY Times Software Developer

      Comment

      Working...
      X