0

I have:

var data = [];

I want to dynamically create string array like this:

for(var i=0; i < files.length; i++){
    data[i].part1 = "abc";
    data[i].part2 = "def";
    data[i].part3 = "ghi"; 
}

Is this possible? I tried it and it complained 'Cannot set property 'part1' of undefined'

Then I want to sort the data array by part1 values so:

data[0] = {3,a,b};
data[1] = {1,a,b};
data[2] = {5,a,b};

becomes:

data[0] = {1,a,b,c};
data[1] = {3,a,b,c};
data[2] = {5,a,b,c};

The reason I want to do this is because after the sort is done, i need to change the

data[i].part2

to something else after sorting!

1 Answer 1

2

You could do this:

for (var i = 0; i < files.length; i++) {
    data[i] = {};
    data[i].part1 = "abc";
    data[i].part2 = "def";
    data[i].part3 = "ghi"; 
}

to set data[i] to an empty object, then fill it piece by piece. Or

for (var i = 0; i < files.length; i++) {
    data[i] = {
        part1: "abc",
        part2: "def",
        part3: "ghi"
    };
}

to set data[i] to the complete object all at once.


I don't understand the data[0] = {3,a,b}; part, though: {3,a,b} is a syntax error and it doesn't resemble your other code (which doesn't mention 3 or a or b).

But you can easily sort an array of objects by a particular property:

data.sort(function (a, b) {
    return (a.part1 > b.part1) - (a.part1 < b.part1);
});

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort for details.

Sign up to request clarification or add additional context in comments.

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.