0

Im trying to sort the name of the link alphabetically, but it says level2.sort is not a function any help is appreciated!

for (let i = 0, l = finalData.length; i < l; i++) {
        const level1 = finalData[i];
        console.log('This is level 1', level1);
        for (let x = 0, y = finalData[i].links.length; x < y; x++) {
            const level2 = finalData[i].links[x];
            level2.sort((a, b) => a.name - b.name);
            console.log('This is level 2', level2);
        }
    }

Level 1 at [0] is {title: "resources" , links:Array(3)}

Level 2 at [0] is {name: "google", path:"www.google.com"}

Level 2 at [1] is {name: "yahoo", path:"www.yahoo.com"}

Level 2 at [2] is {name: "apple", path:"www.apple.com"}


Level 1 at [1] is {title: "TeacherEmails" , links:Array(2)}

Level 2 at [0] is {name: "JoneA", path:"[email protected]"}

Level 2 at [1] is {name: "AndyK", path:"[email protected]"}

and so on

2
  • what are the outputs of the console.logs ? level2 seems to not be an array but an object Commented Apr 11, 2019 at 15:47
  • 2
    Please post finaldata structure. It seems that level2 at certain point is not an array Commented Apr 11, 2019 at 15:47

2 Answers 2

1

You are going too deep here: const level2 = finalData[i].links[x];

This makes level2 not an array which makes sort not work.

Remove the index accessor: finalData[i].links;

You will not need the second for loop either.

And use the sort from MDN for strings:

// sort by name
items.sort(function(a, b) {
  var nameA = a.name.toUpperCase(); // ignore upper and lowercase
  var nameB = b.name.toUpperCase(); // ignore upper and lowercase
  if (nameA < nameB) {
    return -1;
  }
  if (nameA > nameB) {
    return 1;
  }

  // names must be equal
  return 0;
});

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

Your loop would look like this:

for (let i = 0; i < finalData.length; i++) {
    finalData[i].links.sort((a, b) => {
        var nameA = a.name.toUpperCase(); // ignore upper and lowercase
        var nameB = b.name.toUpperCase(); // ignore upper and lowercase
        if (nameA < nameB) {
           return -1;
        }
        if (nameA > nameB) {
           return 1;
        }

        // names must be equal
        return 0;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you this is very helpful!
0

You get this error because level2 is not an Array object, it's an array-like Arguments object.

If you can you external library, like lodash, you can sort by using orderBy method:

_.orderBy(level2, ['name'], ['asc']);

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.