How do I number fields in records?
-
People, hello everyone. Please help me solve one problem:
There is a set of records in which one of the fields is filled with a digit. A record has a unique number in the number field and a pr field, which contains numbers, as well as another set of fields filled with something.
for example (not all options, but an example of possible ones):
I)
1,2,4,5 - to do this - 1,2,3,4 (i.e. 4 becomes 3, and 5 becomes 4)
or
II)
1,3,5 - to do this - 1,2,3 (i.e. 3 becomes 2, and 5 becomes 3)
or
III)
1,4,5 - to do this - 1,2,3 (i.e. 4 became 2 and 5 became 3)
or
IV)
2,4,5 - to do this - 1,2,3 (i.e. 2 became 1, and 4 became 2, and 5 became 3)
Or more fully for i) the example above:
number = 100 has pr = 1; the entry number = 101 has pr = 2; entry number = 223 has pr = 4; the entry number = 190 has pr = 5
Should be:
number = 100 has pr = 1; the entry number = 101 has pr = 2; entry number = 223 has pr = 3; the entry number = 190 has pr = 4
Something I wrote beautifully too - the entries are not arranged in order as I wrote them in I) ... - I just displayed them like that.
In fact, it is necessary to preserve the precedence of the numbers, to renumber them in a sequential row from one.JavaScript Anonymous, Mar 19, 2019 -
If I understand correctly, then you sort by id, if the array is unsorted, and you number them stupidly forycham (as far as I understand, these are objects).
Edit:
Because of the disgusting DevAB96 code, I'll write some normal code.
const arr = [
{ number: 100, pr: 1 },
{ number: 101, pr: 2 },
{ number: 190, pr: 5 },
{ number: 223, pr: 4 }
];
// если порядок оригинального массива нужно отсортировать,
// то: arr.sort
const sortedArr = [...arr].sort((el1, el2) => el1.pr - el2.pr);
sortedArr.forEach((el, index) => {
el.pr = index + 1;
});
console.log(arr);
console.log(sortedArr);Lukas Carson -
Something I wrote beautifully too
Exactly, I even shed a bloody tear from emotion!
I understand that the order does not matter, but I understood it from this fragment of beauty:
entry number = 100 has pr = 1; the entry number = 101 has pr = 2; the entry number = 223 has pr = 4; the entry number = 190 has pr = 5
Should be:
the entry number = 100 has pr = 1; the entry number = 101 has pr = 2; record number = 223 has pr = 3; number = 190 has pr = 4
You can do it like this:
const numbered = records.map((el, index) => ({...el, pr: index + 1}) ) // numbered - новый массив с нужной нумерацией pr
// если нужно изменить на месте, то через forEach изменить свойство prMichael Kidd
2 Answers
Your Answer
To place the code, please use CodePen or similar tool. Thanks you!