Home > Software design >  How sort arrays in js
How sort arrays in js

Time:08-22

There are arrays A and B. We need to add to array C all the values of arrays A and B that are equal in both value and indexes.

A = [a,b,c], B = [c,b,a], C = [b]

Also: to add to array D all unique values from array A that are contained in array B.

A = [d,a,b,c], B = [c,b,a,a], D = [a,b,c]

Is it possible to do this without a nested loop? I can handle the first task, but how do I fill D with values?

for (let i = 0; i < a.length; i  ) {
  if (b[i] === a[i]) {
    c.push(a[i]);
  } else if() {
   // Some code 
  }
}

CodePudding user response:

filter method? (for second question)

let D = A.filter(e => B.includes(e));

adding because you asked for D to contain unique values from A, thanks to @jarmod for pointing this out. You could use filter again to remove duplicates. I found this: Get all unique values in a JavaScript array (remove duplicates)

CodePudding user response:

You can use a Set to keep track of unique values and .has() for efficient lookup in that Set. This code uses only one loop in your code, but several set operations use loops in their internal implementation (to build a set from an Array or convert a set to an Array). That cannot be avoided.

const A = ['e', 'd', 'a', 'b', 'c'];
const B = ['e', 'c', 'b', 'a', 'a'];


function processArrays(a, b) {
    const c = [];
    const aSet = new Set(a);
    const commonSet = new Set();

    for (let i = 0; i < a.length; i  ) {
        if (b[i] === a[i]) {
            c.push(a[i]);
        }
        // if aSet has this value, then add it to commonSet
        if (aSet.has(b[i])) {
            commonSet.add(b[i])
        }
    }
    return { samePositionElements: c, commonElements: Array.from(commonSet) };
}

console.log(processArrays(A, B));

Note, I don't do an if/else here because these are two independent output tests. The first is if the two elements in the same position have the same value. The second is whether it's an element in common with the other array (regardless of position).

This code assumes the two input arrays have the same length. If you wish to support inputs with different length, that can be accommodated with slightly more code.

  • Related