'How do I move values of an array from one array to another [Javascript]
How do I move values of an array from one array to another.
let titels = [];
let notes = [];
let titelArchiv = [];
let noteArchiv = [];
function addNote() {
let titel = document.getElementById('titel');
let note = document.getElementById('note');
titels.push(titel.value);
notes.push(note.value);
}
function deleteNote(i) {
titelArchiv.push(titel.value);
noteArchiv.push(note.value);
}
I've already written a lot but I have a mistake in thinking and can't get any further. So I want to delete the title at position i and the note at position i from the arrays and insert them into the archive arrays
Solution 1:[1]
You can use Array.splice() to achieve this. For the demo purpose I am just showing it one array (titles).
Working Demo :
let titles = ['title1', 'title2', 'title3', 'title4'];
let archivedTitles = [];
function removeElement(id) {
archivedTitles.push(titles.splice(id, 1));
}
removeElement(1);
console.log(titles); // removed that element from an original array
console.log(archivedTitles); // Pushed removed element in the archieved array
Solution 2:[2]
Assuming that i = index
let titels = [];
let notes = [];
let titelArchiv = [];
let noteArchiv = [];
function addNote() {
let titel = document.getElementById('titel');
let note = document.getElementById('note');
titels.push(titel.value);
notes.push(note.value);
}
function deleteNote(i) {
titelArchiv.push(...titels.splice(i, 1));
noteArchiv.push(...notes.splice(i, 1));
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Rohìt JÃndal |
| Solution 2 | pdzxc |
