1

I have a function buildList with an array of numbers in argument. I also have 11 elements which are numbers and i want to know if these elements exists in the array and if one element doesn't exist i push it in another array.

Actually it looks like that:

public static buildList(numbers[]) {
const newArray= [];
    if (numbers.find(element => element === ELEMENT_ONE) === undefined ) {
      newArray.push(ELEMENT_ONE);
    }
    if (numbers.find(element => element === ELEMENT_TWO) === undefined ) {
      newArray.push(ELEMENT_TWO);
    }
    ....
}

My current intuition was to create a new array with the 11 elements and do a for each but i'm not pretty sure the performance will be better... Is there any way to improve this code ? because i do the same things for the 11 elements

2 Answers 2

2

function buildList(numbers) {
  let newArray = [];
  elevenElements = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

  // Use this logic to filter elements.
  newArray = elevenElements.filter(d => numbers.some(y => y === d))
  return newArray;
}

const result=buildList([1, 8, 9]);
console.log(result)

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

Comments

1
    public static buildList(numbers[]) {
      const newArray = [];
      elevenElements = [1,2,3,4,5,6,7,8,9,10,11]

// Use this logic to filter elements.
      newArray = elevenElements.filter(d => !numbers.includes(d))
    }

2 Comments

Prints just an error: SyntaxError: unexpected token: 'static'. FF here.
@ceving I have just written the logic requested by the user.

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.