Sorting Object Array javascript

Asked

Viewed 242 times

0

I am writing a library that implements several sorting algorithms all going well until I execute the sorting of an array of objects.

const exec = (array, fnCompare) =>{
    return sort.bubble(array, fnCompare);
  }

  describe('Array Obejetos', ()=> {
    let array_in = [
      {name: "Alex", age: 12},
      {name: "Max", age: 34},
      {name: "Mary", age: 9},
      {name: "Justin", age: 53}
    ];

    let array_out_asc = [
      {name: "Mary", age: 9},
      {name: "Alex", age: 12},
      {name: "Max", age: 34},
      {name: "Justin", age: 53}
    ]

    const fnASC = (a,b) => {
      return a.age < b.age; //linha onde o console reclama que o erro ocorreu
    };

    it('Ordenação crescente', ()=> {
      assert.deepEqual(array_out_asc, exec(array_in, fnASC));
    });
  });

But I end up having the following exit on my unit test:

 24 passing (29ms)
  1 failing

  1) Bubble Array Objetos Ordenação crescente:
     TypeError: Cannot read property 'age' of undefined
      at fnASC (test/bubblesort.spec.js:85:23)
      at core/bubble.js:25:10
      at Array.forEach (native)
      at Object.array.forEach [as bubble] (core/bubble.js:24:11)
      at exec (test/bubblesort.spec.js:10:17)
      at Context.<anonymous> (test/bubblesort.spec.js:89:39)

The error says that it was not possible to read the property acts, however if I add a log console within the fnASC function described above it prints the object perfectly. Does anyone have any idea what might be going on ?

  • What is happening is that at a certain point in the execution one tries to read the act property of an object Undefined, i.e., an empty position of the/JSON vector. Try to check the stopping condition of your sorting function, to ensure that you never fall into an invalid position.

  • The one with the file test/bubblesort.spec.js?

  • There is a significant amount of code to put here I will leave the link of github https://github.com/1fabiopereira/node-sort-library if you want to take a look, and I will check what you told me.

  • You were @Sergio correct my stop condition performed once again, thank you very much.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.