Home > Back-end >  Function Array not returning new array
Function Array not returning new array

Time:10-21

For some reason I acquire the same array but not the new array that repeats. I don't receive the new array that is supposed to be free of non-repeating values. I attempted to filter out the array through "[i]" and if it did not equal the value it pushes

Problem: Take the following array, remove the duplicates, and return a new array. You are more than likely going to want to check out the Array methods indexOf and includes. Do this in the form of a function uniquifyArray that receives an array of words as a argument.

const words = [
  'crab',
  'poison',
  'contagious',
  'simple',
  'bring',
  'sharp',
  'playground',
  'poison',
  'communion',
  'simple',
  'bring',
]

function uniquifyArray(arrays) {
  if (arrays.length === 0) {
    return null
  }

  let newArray = []

  for (i = 0; i < arrays.length; i  ) {
    if (newArray[i] !== arrays[i]) {
      newArray.push(arrays[i])
    }
  }

  return newArray
}

CodePudding user response:

You can possibly just use a Set here. Example below:

function uniquifyArray(arrays) {
    return arrays === null ? null : Array.from(new Set(arrays));
}

CodePudding user response:

Using a set would probably be a better way to achieve this. But since your requirements ask for things to be done this way, here is the working version:

const words = [
  "crab",
  "poison",
  "contagious",
  "simple",
  "bring",
  "sharp",
  "playground",
  "poison",
  "communion",
  "simple",
  "bring",
];

function uniquifyArray(arrays) {
  if (arrays.length === 0) {
    return null;
  }

  let newArray = [];

  for (i = 0; i < arrays.length; i  ) {
    if (!newArray.includes(arrays[i])) {
      newArray.push(arrays[i]);
    }
  }

  return newArray;
}
  • Related