To remove object from array using JavaScript, we call the splice method.
For instance, we write
someArray.splice(x, 1);
to call someArray.splice with x and 1 to remove the item at index x from someArray in place.
Web developer specializing in React, Vue, and front end development.
To remove object from array using JavaScript, we call the splice method.
For instance, we write
someArray.splice(x, 1);
to call someArray.splice with x and 1 to remove the item at index x from someArray in place.
To remove all duplicates from an array of objects with JavaScript, we convert the objects to JSON strings and put them in a set.
For instance, we write
const things = [];
things.push({ place: "here", name: "stuff" });
things.push({ place: "there", name: "morestuff" });
things.push({ place: "there", name: "morestuff" });
const newThings = Array.from(new Set(myData.map(JSON.stringify))).map(
JSON.parse
);
to call myData.map with JSON.stringify to return an array of JSON strings converted from the objects in the things array.
And then we convert the array to a set with Set to remove the duplicate strings.
Next we call Array.from to convert the set back to an array.
And then we call map with JSON.parse to convert the JSON strings back to objects.
To check if an array contains any element of another array in JavaScript, we use the some method.
For instance, we write
const arr1 = ["apple", "grape"];
const arr2 = ["apple", "banana", "pineapple"];
const found = arr1.some((r) => arr2.includes(r));
to call arr1.some with a callback that checks if the item being iterated through r is in arr1 is in arr2 with arr2.includes.
If the callback returns true, then some returns true.
To generate HTML with Node.js, we call the createServer method.
For instance, we write
const http = require("http");
http
.createServer((req, res) => {
res.write("<html><head></head><body>");
res.write("<p>Write your HTML content here</p>");
res.end("</body></html>");
})
.listen(1337);
to call createServer with a callback that calls res.write to write HTML as the response body.
We call res.end to finish writing the response body.
To send HTML file to client with Node, we call the sendFile method.
For instance, we write
const app = express();
app.get("/test", (req, res) => {
res.sendFile("views/test.html", { root: __dirname });
});
to call res.sendFile with the template’s path to render the template.
root is the root folder for the template files.