John Snow John Snow - 7 months ago 7
Javascript Question

Original Array value after modification

var a = ["11", "22", "46", "22", "11", "55"];

console.log(a); // [ '11', '22', '46', '22', '11', '55' ]

// Calculates my values
var b = a.map(function(num) {
return num.split('')
.map(Number)
.reduce(function(a, b) {
return a + b;
});
});
console.log(b); // [ 2, 4, 10, 4, 2, 10 ]

// Finds my biggest value
var c = 0;
for (var i = 0; i < b.length; i++) {
if (b[i] > c) {
c = b[i];
}
}
console.log(c); // 10

// Sorts my array
var d = b;
d.sort(function(a, b) {
return a - b;
});
console.log(d); // [ 2, 2, 4, 4, 10, 10 ]


I am having a problem here. The
var d
tells me about these following arrays
[ 2, 2, 4, 4, 10, 10 ]
. They originally come from this array
["11","22","46","22","11","55"]
. I am also sorting them out. So at the end in
var d
I am receiving two 10s at the end of my array. Let's say that
d[4]
originally came from
a[2]
and
d[5]
came from
a[5]
. How can I make the code tell me 10's original value from my first array. Let's say we get
2, 2, 4, 4, 10, 10
. I want this last 10 from right side value to tell me it came from
"55"
. Is there a way for me to do that?

Answer

While the other solution from Joseph the Dreamer points to the right direction, lacks it the concrete wanted result of the question.

This proposal uses an array with objects and keeps the former sort order with pos and the wanted cobined number.

After sorting, you can access the last element and get the original value from the new array.

var a = ["11", "22", "46", "22", "11", "55"],
    b = a.map(function (aa, i) {
        return {
            value: aa,
            pos: i,
            number: aa.split('').map(Number).reduce(function (a, b) { return a + b }, 0),
        };
    });

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

document.write(b[b.length - 1].value);
document.write('<pre>' + JSON.stringify(b, 0, 4) + '</pre>');

function myfun(a) {
    var b = a.map(function (aa, i) {
            return {
                value: aa,
                pos: i,
                number: aa.replace(/-/g, '').split('').map(Number).reduce(function (a, b) { return a + b }, 0),
            };
        });

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

document.write('<pre>' + JSON.stringify(myfun(['1-2-3-4', '5-67-7-8', '2-3545-4-6-8-1', '3-3-4-1-3-4', "3-2-4-5-7", '2-3-4-5-7']), 0, 4) + '</pre>');

Comments