Home > Mobile >  How to add extra values from 2 arrays to end of new array
How to add extra values from 2 arrays to end of new array

Time:09-21

For example, if I have 2 arrays being: let array1 = [1,2,3]; and let array2 = [5,6,7,8,9], how would I create a new 3rd array that only contains the elements from array2 that are at the extra indexes (so the new array would only contain [8,9] since they are at index 3 and 4).

Thanks!

CodePudding user response:

You can use the Javascript slice() function

arr1 = [1,2,3]
arr2=[5,6,7,8,9]

arr3 = arr2.slice(arr1.length , arr2.length)

console.log(arr3)

CodePudding user response:

There are plenty of ways to do that, here's a solution that uses slice method with a negative index. That negative index is (array2.length - array1.length) * -1.

const array1 = [1, 2, 3],
  array2 = [5, 6, 7, 8, 9],
  sliceArray = (a1, a2) => a2.length <= a1.length ? [] : a2.slice((a2.length - a1.length) * -1)


console.log(sliceArray([], [])); // returns: []
console.log(sliceArray([1, 3, 6], [1, 2])); // returns: []
console.log(sliceArray(array1, array2)); // returns: [8, 9]

CodePudding user response:

let array1 = [1,2,3,8,9];
let array2 = [5,6,7];
let array3=array1.length > array2.length ?array1.slice(array2.length,array1.length):array2.slice(array1.length,array2.length)
console.log(array3);

Use ternary operator and slice method

CodePudding user response:

You can use a function that will find the longer array and slice it for you. That way, you don't need to know in advance which array is longer:

function collectExtra (arrayA, arrayB) {
  if (arrayA.length === arrayB.length) return [];

  const [shorter, longer] = [arrayA, arrayB]
    .sort((a, b) => a.length - b.length);

  return longer.slice(shorter.length);
}

const array1 = [1,2,3];
const array2 = [5,6,7,8,9];

const result = collectExtra(array1, array2);
console.log(result); // [8, 9]

const result2 = collectExtra(array2, array1);
console.log(result2); // [8, 9]

  • Related