0

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

5
  • var data = @json($data) doesn't look like valid JS? Commented Apr 25, 2021 at 19:03
  • it's valid for laravel php. php array to js array conversion Commented Apr 25, 2021 at 19:04
  • So what's the javascript tag for? Commented Apr 25, 2021 at 19:11
  • stackoverflow.com/questions/33326699/… Commented Apr 25, 2021 at 19:41
  • you can find your answer from this. thanks Commented Apr 25, 2021 at 19:41

3 Answers 3

2

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"]);
}
Sign up to request clarification or add additional context in comments.

Comments

1

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')

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.