I have an array that has 3 data in each index
variable
var data = @json($data)
output
(6) [{…}, {…}, {…}, {…}, {…}, {…}] 0: {day: "Saturday", totalIncome: 0, totalExpense: 300} 1: {day: "Sunday", totalIncome: 0, totalExpense: 0} 2: {day: "Monday", totalIncome: 0, totalExpense: 0} 3: {day: "Tuesday", totalIncome: 0, totalExpense: 0} 4: {day: "Wednesday", totalIncome: 500, totalExpense: 0} 5: {day: "Thursday", totalIncome: 0, totalExpense: 0} length: 6
I want to make 3 array like
var days = datas.day; var incomes = datas.totalIncome; var expenses = data.totalExpenses;
what should I do now to make this 3 arrays from data. please help
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Maybe something like this in vanilla JS:
const days = [], incomes = [], expenses = []; for (let i = 0; i < data.length; i++) { days.push(data[i]["day"]); incomes.push(data[i]["totalIncome"]); expenses.push(data[i]["totalExpense"]); }
Method 2
Map your data into new arrays.
var days = datas.map(function(obj) { return obj['day']; }); var incomes = datas.map(function(obj) { return obj['income']; }); var expenses = datas.map(function(obj) { return obj['expenses']; });
If you have lodash
installed.
var days = _.pluck(datas, 'day')
Method 3
Use native flatMap
function, for example:
var groupBy = key => {
return [
{day: "Saturday", totalIncome: 0, totalExpense: 300},
{day: "Sunday", totalIncome: 0, totalExpense: 0},
{day: "Monday", totalIncome: 0, totalExpense: 0},
{day: "Tuesday", totalIncome: 0, totalExpense: 0},
{day: "Wednesday", totalIncome: 500, totalExpense: 0},
{day: "Thursday", totalIncome: 0, totalExpense: 0}
].flatMap(v => v[key])
}
const days = groupBy('day')
console.log(days)
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0