1

I have the following 2 arrays:

groupedObjects: [
    { value: 125, currency: "EUR" }, 
    { value: 100, currency: "USD" }, 
    {value: 320, currency: "RON" }
]
groupedObjects1: [
    { value: 500, currency: "EUR" }, 
    { value: 280, currency: "RON" }
]

How can I have those 2 arrays look identical? I would like that second array, after code looked like:

[
    { value: 500, currency: "EUR" }, 
    { value: 0, currency: "USD" }, 
    { value: 280, currency: "RON" }   
]

I have tried this code:

if ($(groupedObjects).length > $(groupedObjects1).length) {
    _.each(groupedObjects,function(obj){
        i++;
        _.each(groupedObjects1,function(obj1){
            if(obj.currency != obj1.currency) {
                alert('Test');
                groupedObjects1.push ({
                    value: '',
                    currency: ''
                });
            }                               
        });
    });
} 

I want that both arrays would be sorted by currency and both of them should have same number of elements, no matter wich array would be larger

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
rosuandreimihai
  • 656
  • 3
  • 16
  • 39
  • possible duplicate of [Insert Item into Array at a Specific Index](http://stackoverflow.com/questions/586182/insert-item-into-array-at-a-specific-index) – Itay May 24 '14 at 14:48

3 Answers3

0
    groupedObjects= [
        { value: 125, currency: "EUR" }, 
        { value: 100, currency: "USD" }, 
        {value: 320, currency: "RON" }
    ];
    groupedObjects1= [
        { value: 500, currency: "EUR" }, 
        { value: 280, currency: "RON" }
    ];


if ($(groupedObjects).length > $(groupedObjects1).length) {

var newArray = [];
$.each(groupedObjects, function (key, value) {
    var flag = false;
    var breakout = false;
    flag = (function () {
        $.each(groupedObjects1, function (key1, value1) {
            if (value.currency === value1.currency) {
                newArray.push(value1);
                breakout = true;
                return false;
            }

        });
        if (!breakout) {
            return true;
        }
    })();
    if (flag) {
        newArray.push({
            value: 0,
            currency: value.currency
        });
    }
});
groupedObjects1 = newArray;

}
mohamedrias
  • 18,326
  • 2
  • 38
  • 47
  • Thank you for your answer, but now I am having an issue, that is due to the fact that sometimes the arrays are equal (groupedObjects == groupedObjects1) but with different values. In this case, how can I add to both of the arrays the missing values? – rosuandreimihai May 29 '14 at 18:41
0

Well, there are a couple of ways to approach this, and hacking together a function that adds blank values into an array is certainly one of them, but a more object-oriented approach is going to help you a lot more.

I'm not sure how "advanced" you are with javascript, so I'm sorry if it sounds like I'm babying you.

The first thing we want to do is set up a Currency class. There are a few ways to do this, but I prefer the one below, most likely because I'm from a C++ background. Feel free to use another method if you wish.

function Currency(type, quantity){
    this.type = type;
    this.quantity = quantity;
}

If you want, you could add some validation, such as making sure that quantity is greater than 0 or that type is a valid currency. You could also make those properties private and implement accessors for them, but I'm just trying to keep it simple for now. If you'd like, you could extend it for each currency, so you could say new USD(280) to create a USD object with a value of 280.

So, now that we have our currencies settled, we can think about how we want to store them. We want to make sure that if we haven't added a currency, its quantity is equal to 0. To do this, we'll instantiate an object for each type of currency, then set its value as necessary.

Here's a really simple implementation:

function CurrencyList(){
    var valid_currencies = ["EUR", "RON", "USD"];
    this.currencies = [];
    for(i in valid_currencies){
        this.currencies[i] = new Currency(valid_currencies[i], 0);   
    }
}

I just created an array of valid currencies, iterate through them, and create a "public" property with the valid currency object. I store it in an array like in you have already, it's just in an object.

We're not done yet, though. What if some nefarious person deleted an element in our array? We'd be back to your original problem. We can solve this by making currencies invisible outside the object.

function CurrencyList(){
    var valid_currencies = ["EUR", "RON", "USD"];
    currencies = [];
    for(i in valid_currencies){
        currencies[i] = new Currency(valid_currencies[i], 0);   
    }
}

Now if we try something like this:

var currency_list = new CurrencyList();
alert(currency_list.currencies[0]);

We get an error, which means that our array cannot be modified from outside.

This introduces another problem: what if we want to view an element in our array? The answer is to implement an accessor (a "get") method.

All we have to is create a "public" property and set it equal to a function, like this:

this.at = function(index){
    return currencies[index];   
}

Now we can access a currency like this:

var currency_list = new CurrencyList();
alert(currency_list.at(0));

This is it all put together:

function CurrencyList(){
    var valid_currencies = ["EUR", "RON", "USD"];
    currencies = [];
    for(i in valid_currencies){
        currencies[i] = new Currency(valid_currencies[i], 0);   
    }

    this.at = function(index){
        return currencies[index];   
    }
}

function Currency(type, quantity){
    this.type = type;
    this.quantity = quantity;
}

This will ensure that you can't have mismatched arrays, so we don't have to bother with a hacky, post hoc solution. In other words, it doesn't solve your problem, but rather prevents the problem from ever existing, which is an even better solution. It also ensures that your array is sorted by currency, because the elements will always be in the order that you specify in your constructor.

Meredith
  • 844
  • 6
  • 17
0

Don't use push() Insert de item in the same index.

Use that:

if ($(groupedObjects).length > $(groupedObjects1).length) {
_.each(groupedObjects,function(obj){
    i++;
    _.each(groupedObjects1,function(index, obj1){
        if(obj.currency != obj1.currency) {
            alert('Test');
            groupedObjects1[index] = ({
                value: '',
                currency: ''
            });
        }                               
    });
});

}

Erik Lucio
  • 948
  • 7
  • 8