-1

I have 2 arrays and I want to merge and sort arrays like I have mentioned in the title, I have searched online but could find solution for mine. I am able to merge 2 arrays using concat method but that is not what I want.

var hege   = ["a", "b", "c"];
var stale  = ["x", "y", "z"];
var result = ["a", "x", "b", "y", "c", "z"];

both of these arrays do not have static values but both have similar number of items

I am not able to try it because I dont have any clue

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64

2 Answers2

1

You could use .flatMap() on your hege array to map to a new array, which contains the values from your original array coupled with the value at the same index from your other array:

const hege = ["a", "b", "c"];
const stale = ["x", "y", "z"];

const res = hege.flatMap((c,i) => [c,stale[i]]);
console.log(res);

For something a little more browser compatible, you could use .reduce() instead, to reduce to a new array ([]) which contains each pair like so:

const hege = ["a", "b", "c"];
const stale = ["x", "y", "z"];

const res = hege.reduce((acc, elem, i) => [...acc, elem, stale[i]], []);
console.log(res);

Or, if you'd like, here's a functional programming with currying approach where you can specify how the two elements should join with a joining method:

const hege = ["a", "b", "c"],
  stale = ["x", "y", "z"];

const join = x => y => [x, y],
  head = ([x]) => x,
  rest = ([x, ...y]) => y,
  isset = ({length:x}) => ({length:y}) => x && y,
  merge = x => y => [...x, ...y];

const zip = f => a => b =>
  isset(a)(b) ? merge(f(head(a))(head(b)))(zip(f)(rest(a))(rest(b))) : [];

console.log(zip(join)(hege)(stale));
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
0

If they have the same number of elements, you can just use (pseudo-code since you haven't provided a language):

def intermix(list1, list2):
    result = []
    for index = 0 to list1.len - 1 inclusive:
        result.append(list1[index])
        result.append(list2[index])

If you want to be able to handle lists of different lengths, you can do that by simply processing the common bit then processing the remainder of the longer list, something like:

def intermix(list1, list2):
    # Common bit.

    commonLen = min(list1.len, list2.len)
    for index = 0 to commonLen - 1 inclusive:
        result.append(list1[index])
        result.append(list2[index])

    # Excess bit (at most one loop will execute).

    for index = commonLen to list1.len - 1 inclusive:
        result.append(list1[index])

    for index = commonLen to list2.len - 1 inclusive:
        result.append(list2[index])

This algorithm will also work with lists of the same length.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953