I am new to JavaScript, I use operations like insertion and deletion of elements. Arrays are not good in insertion and deletion operations. Are there any alternative other than Array in JavaScript to perform these operations? Like we have ArrayList in Java.
function maintest() {
deletelem(3);
insertelem(9845568);
}
function deletelem( num ) {
var value = num;
var arr = [1, 2, 3, 4, 5, 3]
arr = arr.filter(function(item) {
return item !== value
})
console.log(arr);
}
function insertelem( num ) {
var value = num;
var arr = [1, 2, 3, 4, 5, 3]
arr.splice(2, 0, num);
console.log(arr);
}
<body onload="maintest()">
<div id="mainDiv"></div>
</body>
I am new to JavaScript, I use operations like insertion and deletion of elements. Arrays are not good in insertion and deletion operations. Are there any alternative other than Array in JavaScript to perform these operations? Like we have ArrayList in Java.
function maintest() {
deletelem(3);
insertelem(9845568);
}
function deletelem( num ) {
var value = num;
var arr = [1, 2, 3, 4, 5, 3]
arr = arr.filter(function(item) {
return item !== value
})
console.log(arr);
}
function insertelem( num ) {
var value = num;
var arr = [1, 2, 3, 4, 5, 3]
arr.splice(2, 0, num);
console.log(arr);
}
<body onload="maintest()">
<div id="mainDiv"></div>
</body>
Share
Improve this question
edited Feb 13, 2020 at 17:26
Rapsssito
1501 silver badge9 bronze badges
asked Feb 13, 2020 at 17:10
karansyskaransys
2,73910 gold badges50 silver badges91 bronze badges
2
-
2
A Java
ArrayList
is basically an array; its performance characteristics are basically exactly the same as a JavaScript array. – Pointy Commented Feb 13, 2020 at 17:12 - Thanks Pointy, are there any better way to insert and delete elements in java script, I want to improve performance of my application – karansys Commented Feb 13, 2020 at 17:14
1 Answer
Reset to default 8Arrays are JavaScript's only built-in ordered container type (well, almost; keep reading). There is no "list" in the standard library, though creating one wouldn't be hard; any of the standard "linked list" algorithms is easily implemented in JavaScript. Arrays in JavaScript are inherently sparse, and separately array operations on non-sparse arrays are very fast, so it's not mon to find that you need a "list" class specifically.
Depending on your use case, you may find one of these handy:
- An object with named properties, rather than numeric indexes.
- A
Map
, which maps keys to values. Keys and values can be any type. - A
Set
, which is a set of unique values. Values can be of any type.
Other than that, I wouldn't be surprised if a search turned up some prebuilt "list" classes you could use.