简体   繁体   中英

Creating arrays in JavaScript by comparing values in another array

In JavaScript, I'm trying to create arrays based on the values of another array and I'm having difficultly.

I've got an array of dates in string format (dates) eg

["30/09/2015", "31/10/2015", "30/11/2015", "31/12/2015"]

I've got an Object to represent multiple bank accounts (balancesSortByAccId) eg

Cash - (Array size: 3)
id: 1, date: "30/09/2015", balance: 30
id: 2, date: "31/10/2015", balance: 50
id: 3, date: "30/11/2015", balance: 100

Natwest - (Array size: 2)
id: 4, date: "30/11/2015", balance: 400
id: 5, date: "31/12/2015", balance: 200

Whilst looping through all the accounts in balancesSortByAccId, I want to be able to create an array for the balance at each date in the dates array ie

[30, 50, 100, null]
[null, null, 400, 200]

How could I achieve this?

UPDATE: jsfiddle code - https://jsfiddle.net/gx8bLehb/

The easiest way would be to transform your cash and natwest arrays into a hash sorted by date, something like balancesByDate :

    var balancesByDate = _.groupBy(cash, function(entry) {return entry.date});

Then use an array map() function, eg from lodash to iterate the dates array and for each date look up the account line in the balancesByDate hash. From that line, return the balance property in the map function.

dates.forEach(function(date){
  if (balancesByDate[date]) {
    results.push(_.map(balancesByDate[date], function(line){
       return line.balance;
    }));
  } else {
    results.push(null);
  }
});

However, you need to be aware that your dataset most likely could contain duplicate balances for a day, you should plan for that (my code returns an array for each day).

https://jsfiddle.net/hdpuuc5d/1/

A solution in plain javascript with a helper object for the dates:

 var dates = ["30/09/2015", "31/10/2015", "30/11/2015", "31/12/2015"], datesObj = dates.reduce(function (r, a, i) { r[a] = i; return r; }, {}), balances = { Cash: [ { id: 1, date: "30/09/2015", balance: 30 }, { id: 2, date: "31/10/2015", balance: 50 }, { id: 3, date: "30/11/2015", balance: 100 } ], Natwest: [ { id: 4, date: "30/11/2015", balance: 400 }, { id: 5, date: "31/12/2015", balance: 200 } ] }, result = {}; Object.keys(balances).forEach(function (k) { result[k] = Array.apply(null, { length: dates.length }).map(function () { return null; }); balances[k].forEach(function (a) { result[k][datesObj[a.date]] = a.balance; }); }); document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>'); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM