{ }codelper

Learn › JavaScript

Data · 13

Editing lists

Contains, remove, reverse, swap, fill with one value, copy.

After a list is made you can still take items out and change their order.
The example below keeps a copy of a list of cards, asks whether a number is in it and removes it if so, removes the first card, reverses the list, and swaps the first two cards.
Then it prints the edited list, the copy of the original, and a new list filled with zeros.

const lines = require("fs").readFileSync(0, "utf8").trim().split("\n");const cards = lines[1].trim().split(/\s+/).map(Number);const x = Number(lines[2]);const original = [...cards]; // 복사해 둬요if (cards.includes(x)) {  console.log("yes");  cards.splice(cards.indexOf(x), 1); // 값으로 빼기: 자리를 찾아서 하나만} else {  console.log("no");}cards.splice(0, 1); // 자리로 빼기: 0번cards.reverse();[cards[0], cards[1]] = [cards[1], cards[0]]; // 자리 바꾸기const blank = new Array(cards.length).fill(0); // 0으로 채운 새 목록console.log(cards.join(" "));console.log(original.join(" "));console.log(blank.join(" "));
stdin
5
30 10 40 10 50
10
stdout
yes
10 50 40
30 10 40 10 50
0 0 0

Key points

  • Asking whether a value is in the list answers true or false.
    You can write it in one line instead of comparing in a loop (in C you search with a loop).
  • Removing comes in two kinds.
    By position deletes slot i; by value deletes only the first slot holding that value.
    Either way the items after it move one slot forward.
    What happens when the value is not there differs by language.
  • Reversing turns the order of that same list around; it does not make a new list.
  • Swapping: if you start with a[0] = a[1], the old value of a[0] is gone.
    Move one value into a temporary variable first, or use the syntax that swaps both at once.
  • Filling with one value: make a list from just a size and a starting value, such as a list of n zeros.
  • Copying: lesson 08 said b = a only gives the same list a second name.
    To keep the original, make a separate copy before you edit.
    In Python, JavaScript, Java, C# and Craykon this copy goes only one level deep: copy a grid (a list of lists, lesson 12) and the rows are still shared, so copy each row separately.

How each language writes it

Pythonx in a.
By value a.remove(x) (ValueError if missing), by position a.pop(i) or del a[i].
a.reverse().
a[0], a[1] = a[1], a[0].
[0] * n.
Copy: a.copy()
JavaScripta.includes(x).
By position a.splice(i, 1).
There is no remove-by-value, so find the position with a.indexOf(x) and splice it.
a.reverse().
[a[0], a[1]] = [a[1], a[0]].
new Array(n).fill(0).
Copy: [...a]
TypeScriptSame as JavaScript
JavaOn a List<Integer>: a.contains(x).
By position a.remove(i), by value a.remove(Integer.valueOf(x)) (false if missing).
Collections.reverse(a), Collections.swap(a, 0, 1).
new ArrayList<>(Collections.nCopies(n, 0)).
Copy: new ArrayList<>(a).
An array new int[n] starts filled with zeros
C#On a List<int>: a.Contains(x).
By value a.Remove(x) (false if missing), by position a.RemoveAt(i).
a.Reverse().
(a[0], a[1]) = (a[1], a[0]).
Enumerable.Repeat(0, n).ToList().
Copy: new List<int>(a)
C++The value is there if std::find(a.begin(), a.end(), x) is not a.end().
Remove the found position with a.erase(it), or slot i with a.erase(a.begin() + i).
std::reverse(a.begin(), a.end()), std::swap(a[0], a[1]).
std::vector<int> b(n, 0).
b = a is itself a copy
CArrays have a fixed size and none of these functions.
Search with a loop; to remove, shift the later items one slot forward and reduce the count yourself.
Reverse by swapping from both ends, and swap with a temporary variable t.
Copy with memcpy(b, a, n * sizeof a[0]) — b = a is a compile error
Craykona.Contains(x).
By value a.Remove(x) (false if missing), by position a.RemoveAt(i).
a.Reverse().
Swap with a temporary variable.
NewList(n, 0).
Copy: a.GetRange(0, a.Count)

Common mistakes

Removing a value that is not there removed the last itemJavaScript · TypeScript

const a = [1, 2, 3];
a.splice(a.indexOf(9), 1);
console.log(a);

→ [ 1, 2 ] — when the value is missing indexOf gives -1, and splice(-1, 1) removes the last slot

Check first: const i = a.indexOf(9); if (i !== -1) a.splice(i, 1);

Removing from a list while looping over itPython · JavaScript · TypeScript · Java · C#

a = [1, 1, 2, 3]
for v in a:
    if v == 1:
        a.remove(v)
print(a)

→ Python prints [1, 2, 3] — the next item moves into the removed slot, so the second 1 is skipped. JavaScript's for...of gives the same result. Java stops with ConcurrentModificationException and C# with InvalidOperationException. Only Craykon's foreach walks a snapshot taken when the loop starts, so both 1s are removed and the list is 2 3

Build a new list of the items to keep, or use the dedicated function: Python a = [v for v in a if v != 1], JavaScript a = a.filter(v => v !== 1), Java a.removeIf(v -> v == 1), C# a.RemoveAll(v => v == 1).

Meant to remove the value 1, but slot 1 was removedJava

List<Integer> a = new ArrayList<>(List.of(1, 2, 3));
a.remove(1);
System.out.println(a);

→ [1, 3] — given an int, it removes by position. The 2 in slot 1 is gone

To remove by value write a.remove(Integer.valueOf(1)) → [2, 3].
On [10, 20, 30], a.remove(10) looks for slot 10 and stops with IndexOutOfBoundsException.

How languages differ
Reversing is a command that changes the list itself, so in some languages you must not use its result.
In Python, after b = a.reverse(), b is None.
When you need a new reversed list, use a[::-1] in Python or, in JavaScript, copy and then reverse: [...a].reverse().
And in C, int *b = a; is not a copy but another name pointing at the same array: after b[0] = 9, a[0] is 9 too.

Practice