-3

I want to create a sortable javascript object that looks like this:

myArray = [
  {name: "Jones, James", ef: "35", mem: "2018.12.10"},
  {name: "Smith, Paul", ef: "35", mem: "2018.09.12"},
  {name: "Washington, George", ef: "35", mem: "2018.08.16"}
];

I also plan to sort myArray() by name.

myArray.sort(function(a, b){
  return a.name - b.name;
});

THE JAVASCRIPT:

function store() {
  var myArray = [];

  var i;
  for (i = 0; i < 10; i++) {
    NAME = document.getElementById('P' + i).value;
    EF = document.getElementById('E' + i).value;
    MEM = document.getElementById('M' + i).value;

    // This code doesn't seem to add records to myArray()

    myArray.push({
      name: 'NAME',
      ef: 'EF',
      mem: 'MEM'
    });
  }

  console.log(myArray.length);
}

store();

I sorted the myArray:

0: {name: "Abercrombie, Bill", rank: "1537", uscf: "9999", ef: "3", exp: "2019.01.12", …}
1: {name: "Baken, Clif", rank: "1802", uscf: "9999", ef: "3", exp: "2019.09.18", …}
2: {name: "Kukla, Ollie", rank: "2014", uscf: "0920", ef: "", exp: "2019.08.12", …}
3: {name: "Lincoln, Abraham", rank: "2023", uscf: "0119", ef: "", exp: "2019.09.06", …}
4: {name: "Washington, George", rank: "1563", uscf: "9999", ef: "3", exp: "2019.01.16", …}

How do I iterate over the sorted myArray() to populate the form? I think I need something like this:

console.log(myArray.length);

for (i = 1; i <= myArray.length; i++) {
// where id "P1" is the name input field in the form which we are populating
document.getElementById("P" +i).value = myArray[name];

}
verlager
  • 794
  • 5
  • 25
  • 43
  • what have you tried so far?kindly include that in OP – guradio Nov 09 '18 at 00:02
  • I am new to localStorage and I don't know what I'm doing. I need assistance. I can do some things but this pretty advanced. I'm really in over my head, guradio. – verlager Nov 09 '18 at 00:10
  • 1
    You can store an array or single object in one localStorage key by using JSON.stringify() to set and JSON.parse() in the get. Then loop over that array/object and set values within the loop with very little code needed – charlietfl Nov 09 '18 at 00:22
  • I think: localStorage.setItem('SP4', JSON.stringify(document.getElementById("P4").value))); (is correct). But how do I bring the local storage into a sortable array with JSON.stringify ? – verlager Nov 09 '18 at 00:43
  • What exactly is it you want to sort by? You mention _"P1-P48"_ but what does that relate to? Is it the values in your `` elements or their `id` attributes. It's very confusing because your IDs are `P4`, `E4` and `X4` which really doesn't make sense given _"P1-P48"_ – Phil Nov 09 '18 at 02:34
  • What would you like the result to look like? – Phil Nov 09 '18 at 02:48
  • I have a form with input ID's that I want populated. The basic form is at https:/verlager.com – verlager Nov 09 '18 at 02:52
  • That tells me nothing. What's the point in sorting anything if you just want to populate a bunch of `` values? – Phil Nov 09 '18 at 02:54
  • I want to sort by player name which is ID Px where "x" is an integer 1-48 – verlager Nov 09 '18 at 02:54
  • Please provide examples. Show what you currently have and show what you'd like the result to be – Phil Nov 09 '18 at 02:55
  • I'd like the result to be a sorted list. Sorted by player name. – verlager Nov 09 '18 at 02:56
  • All these comments mean absolutely nothing. Please edit your question with actual examples – Phil Nov 09 '18 at 02:57
  • If I could do that, I would, I really would. – verlager Nov 09 '18 at 02:57
  • You can. [Edit your question](https://stackoverflow.com/posts/53217929/edit) to show some examples of actual data and what you'd like the result to look like. It should not be difficult – Phil Nov 09 '18 at 02:58
  • I am lost. Simply in over my head. – verlager Nov 09 '18 at 02:58
  • OK I edited the original question. I don't understand the difficulty of this issue. User types names. I want the names sorted based on local storage. – verlager Nov 09 '18 at 03:07
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/183334/discussion-between-verlager-and-phil). – verlager Nov 09 '18 at 04:00
  • I get it. Sorry, I didn't understand what you met by "give more examples". My bad. – verlager Nov 09 '18 at 16:14
  • were you be able to fix the problem? – solimanware Nov 10 '18 at 02:27
  • No, I'm still in the dark. Sorry for my incompetence. – verlager Nov 10 '18 at 03:47
  • I don't see what any of this (or the previous question edit) has anything to do with local storage. What are you actually trying to accomplish? Do you want to read the data in a filled out form on https://verlager.com/ and then sort it by name? Or do you want to read some data from local storage, sort by name and fill out the form? – Unglückspilz Nov 11 '18 at 19:28
  • I took the initiative of trying to solve this myself. In the interest of simplicity, I omitted the local storage code because it is so simple yet unneeded. We need this sorted so that we can spot duplicate entries. – verlager Nov 11 '18 at 21:46
  • *I want to create a sortable JavaScript object*. Object keys can't be sorted. You're out of luck with that. Use an Array if you require sorting. – Scott Marcus Nov 12 '18 at 00:50

3 Answers3

1

There are a few issues with the code:

  • you are not declaring the variables NAME, EF, MEM.

    This means these are implicit globals (!) and your code might have unintended side-effects.

    Solution: use var, let or even better, const to declare these variables in the block scope.

  • You are pushing strings, not variables.

    when you do myArray.push({name: 'NAME'}) you are saying put the string value 'NAME' as the value for name.

    Solution: remove the quotes, use name: NAME, or even better, change the variable to name and use the ES2015 shorthand notation:

    myArray.push({name, ef, mem});

  • prefer to use const if you are not reassigning variables. Use let in all other cases.

    This simply makes your code more robust as they have fewer quirks than using the old var.

Example:

function store() {
  const myArray = [];

  for (let i = 0; i < 10; i++) {
    // Replaced getElementByID since it's not relevant
    const name = 'some name';
    const ef = 'some string';
    const mem = 'some value';

    // This code doesn't seem to add records to myArray()

    myArray.push({name, ef, mem});
  }

  console.log(myArray.length);
}

store();
lucascaro
  • 16,550
  • 4
  • 37
  • 47
1

Since you use use jQuery, why not build myArray like this:

for (n = 1; n <= 3; n++) {
  myArray.push({
    name: $('#P' + n).val(),
    ef: $('#E' + n).val(),
    mem: $('#M' + n).val()
  });
}

For sorting the myArray: (credits to the MDN reference as well as this answer)

myArray.sort((a, b) => {
  let nameA = a.name.toUpperCase();
  let nameB = b.name.toUpperCase();
  return nameA < nameB ? -1 : nameA > nameB ? 1 : 0;
});

Then for putting back the myArray values into the corresponding input fields:

myArray.forEach((item, i) => {
  let n = i + 1;
  $('#P' + n).val(item.name);
  $('#E' + n).val(item.ef);
  $('#M' + n).val(item.mem);
  // ... do the same for other fields
});
Sally CJ
  • 15,362
  • 2
  • 16
  • 34
0

Two Steps:

1- Make Array []

2- Sort its items using sort function

remember that localStorage sets and get strings so parse them using JSON.parse() method

Sort Function: (this sorts alphabetically with property name)

Array.prototype.sort()

Demo:

let result = array.sort((a.name, b.name) => a.name - b.name)
solimanware
  • 2,952
  • 4
  • 20
  • 40
  • How can this work...? I have localStorage with SP1 to SP48 as sort items. I don't see any reference to this in the expression you have kindly supplied. – verlager Nov 10 '18 at 03:44
  • First we have the populate a sortable javascript object and then fill in the form from the sorted list. – verlager Nov 11 '18 at 22:04
  • Yes... I updated the answer.. you can mark it as solution if it helps – solimanware Nov 12 '18 at 00:19
  • A simple array is not useful in this case. Please see the orginal question. I have to sort the "array" and then iterate over the "array" to extract vars and populate the form. – verlager Nov 12 '18 at 00:37
  • Sorting object isn't usually useful see this answer: https://stackoverflow.com/questions/1069666/sorting-javascript-object-by-property-value ...so sorting array can be your solution – solimanware Nov 12 '18 at 00:40
  • @Microsmsm `a.name - b.name` works well with numeric values, but for strings, you can use `a.name < b.name ? -1 : a.name > b.name ? 1 : 0` just as in [this answer](https://stackoverflow.com/a/19326174/9217760) and the MDN [reference](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Description). – Sally CJ Nov 12 '18 at 02:06