4

I have two arrays and depending on the element's position in the array it receives a value. Both arrays contain the same elements, but at different positions. I would like to calculate the value for each element, merge the arrays into a single array, and sort the new array.

The only idea I can think of is to turn my initial arrays into arrays of objects, merge those, sort by object value, then map that order into a new array.

var ranks = [],
    objArray1 = [],
    objArray2 = [];

// 'aaa' = 5, 'bbb' = 4, 'ddd' = 3, 'eee' = 2, 'ccc' = 1
var array1 = ['aaa', 'bbb', 'ddd', 'eee', 'ccc'];

// 'ddd' = 5, 'ccc' = 4, 'aaa' = 3, 'bbb' = 2, 'eee' = 1
var array2 = ['ddd', 'ccc', 'aaa', 'bbb', 'eee'];

for (var i = 0, x = 5; i < 5; x--, i++) {
  var obj = {};
  obj[array1[i]] = x;
  objArray1.push(obj);
}

for (var i = 0, x = 5; i < 5; x--, i++) {
  var obj = {};
  obj[array2[i]] = x;
  objArray2.push(obj);
}

// combine both object arrays, match keys, but add values
// should output ranks =[{aaa: 8}, {bbb: 6}, {ccc: 5}, {ddd: 8}, {eee: 3}]

// then sort based on value
// should output ranks = [{aaa: 8}, {ddd: 8}, {bbb: 6}, {ccc: 5}, {eee: 3}]

// then copy keys over to new array while keeping position
// should output var final = ['aaa', 'ddd', 'bbb', 'ccc', 'eee']
3
  • This looks like a homework/interview problem? Commented Dec 27, 2017 at 19:54
  • You just wanna sort the elements by their sum over both arrays? Commented Dec 27, 2017 at 19:54
  • what is an expected result? Commented Dec 27, 2017 at 19:58

2 Answers 2

2

You could skip the part with new temporary arrays with objects and take just an object for counting and then take the sorted keys as result.

var array1 = ['aaa', 'bbb', 'ddd', 'eee', 'ccc'],
    array2 = ['ddd', 'ccc', 'aaa', 'bbb', 'eee'],
    temp = Object.create(null),
    result;

[array1, array2].forEach(a => a.forEach((k, i) => temp[k] = (temp[k] || 0) - i));
result = Object.keys(temp).sort((a, b) => temp[b] - temp[a]);

console.log(result);

Sign up to request clarification or add additional context in comments.

1 Comment

Hey that's really clever! Many thanks! The solution I was working on was just a mess of loops, this is much cleaner.
1

You could use reduce to create object and then use sort on Object.keys.

const array1 = ['aaa', 'bbb', 'ddd', 'eee', 'ccc'];
const array2 = ['ddd', 'ccc', 'aaa', 'bbb', 'eee'];
const n = array1.length;

const r = array1.reduce((r, e, i) => (r[e] = n - i + n - array2.indexOf(e), r), {})
const result = Object.keys(r).sort((a, b) => r[b] - r[a])
console.log(result)

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.