user16731842
user16731842

Reputation: 103

removing array elements containing the certain specified and placing them at last

I have an array generated by a system (downloaded). The order is always random.

I need to remove certain items and place them at last

download_array1 = ["me","father","mother","sister","you","brother","grandfather","grandmother"] download_array2 = ["brother","grandfather","me","grandmother","father","mother","sister","you"] download_array3 = ["you","father","mother","grandmother","sister","me","brother","grandfather",""]

input_always_place_at_last = ["me","you"]

expected output

["father","mother","sister","brother","grandfather","grandmother","me","you"]
["brother","grandfather","grandmother","father","mother","sister","me","you"]
["father","mother","grandmother","sister","brother","grandfather","me","you"]

I have tried with

download_array1.includes(input_always_place_at_last).push(input_always_place_at_last)

Upvotes: 0

Views: 41

Answers (2)

Nitheesh
Nitheesh

Reputation: 19986

Not the unique, but you can implement this using Array.reduce as below.

The variable input_always_place_at_last as name implies expected to be placed always at the end can be concatenated with the result of reduce function.

download_array1 = ["me", "father", "mother", "sister", "you", "brother", "grandfather", "grandmother"];
download_array2 = ["brother", "grandfather", "me", "grandmother", "father", "mother", "sister", "you"];
download_array3 = ["you", "father", "mother", "grandmother", "sister", "me", "brother", "grandfather", ""];
input_always_place_at_last = ["me", "you"];

function updateArray (arr, lastItems) {
  const op = arr.reduce((acc, curr, index) => {
    if (lastItems.indexOf(curr) === - 1 && curr.length > 0) {
      acc.push(curr);
    }
    return acc;
  }, []);
  const output = op.concat(lastItems);
  return output;
}

conole.log(updateArray(download_array1, input_always_place_at_last));
conole.log(updateArray(download_array2, input_always_place_at_last));
conole.log(updateArray(download_array3, input_always_place_at_last));

Upvotes: 0

charlietfl
charlietfl

Reputation: 171679

There are several different approaches to doing this. The most basic is to check the index of the item and splice the array to remove it and push it to end of array

download_array1 = ["me","father","mother","sister","you","brother","grandfather","grandmother"] 

input_always_place_at_last = ["me","you"]

for(let item of input_always_place_at_last){
  const idx = download_array1.indexOf(item);
  if(idx > -1){
    download_array1.splice(idx,1);
    download_array1.push(item)
  }
}

console.log(download_array1)

Upvotes: 1

Related Questions