teleren/devto huggingface dataset:
How to subtract objects from an array of objects by id in Javascript
Tags: javascript, node
Published: 2022-09-29 18:19:47

---
title: How to subtract objects from an array of objects by id in Javascript
published: true
description: in this case we have to subtract the elements of the first from the second array by id
tags: javascript, nodejs
# cover_image: https://direct_url_to_image.jpg
# Use a ratio of 100:42 for best results.
---
Considering the case of wanting to add data to the database but without having duplicates.

Therefore we have two objects: one with my data in the database and the second with the data to add.

Respectively in the example called: **records** and **mainArr**.

As the title says, in this case we have to subtract the elements of the first (**records**) from the second (**mainArr**) array by id.

There are many algorithms that can be adopted, below is an example:

```js
const records = [
  {
    id: 1,
    name: "example1"
  },
  {
    id: 2,
    name: "example2"
  },
  {
    id: 3,
    name: "example3"
  },
  {
    id: 4,
    name: "example4"
  },
];

const mainArr = [
  {
    id: 3,
    name: "example3"
  },
  {
    id: 4,
    name: "example4"
  },
  {
    id: 5,
    name: "example5"
  },
  {
    id: 6,
    name: "example6"
  },
];

const recordsById = records.reduce((ac, record) => {
  if (record.id) {
    return {
      ...ac,
      [record.id]: record
    }
  }
  return ac
}, {});

const objClean = mainArr.filter((item) => {
  const isDuplicated = recordsById[item.id];
  return !isDuplicated;
});

console.log(objClean);
```
We use [reduce](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce) to conveniently obtain an array of objects with the identifier as key and the object itself as value.

We will then have a result similar to:

```js
 recordsById: {
    1: { name: "example1", id: 1 },
    2: { name: "example2", id: 2 },
    3: { name: "example3", id: 3 },
    4: { name: "example4", id: 4 },
  }
```

Then through the [filter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) method we can check if an element of my second array (**mainArr**) contains an element of the created mapping.

We will output my clean object (**objClean**).

Below is a more compact version of the same logic:


```js
const recordsById = records.reduce((ac, record) => {
  return record.id ? { ...ac, [record.id]: record } : ac;
}, {});

const objClean = mainArr.filter(item => !recordsById[item.id]);
```
Harmony ✨- Create, upload, edit (multiple) files on the fly, in the browser and track them with Git, via Web Assembly.
Tags: webassembly, git, react, devjournal
Published: 2022-09-29 18:04:23

I write my first post here to present **Harmony**. My latest project.


![Harmony view](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/64s4x97fqkwj0dbr8d93.png)

Some months ago, I built [Nova](https://github.com/thomscoder/nova-git) a Git playground in Go in which you can clone repositories, create files, branches, commits etc... all in-memory.

What does that have to do with [Harmony](https://github.com/thomscoder/harmony) ? Well, I'm currently  experimenting with WebAssembly and the first idea that I had was to port Nova to the Web to give other people a better UX.


![Harmony editor](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s1a022p4o20pgh6r0lze.png)

So Golang -> WASM -> Javascript -> React BOOM! 
I can finally present a [stable version of Harmony](https://harmonyland.vercel.app).

What Harmony does is simple: 
- Allows the creation, upload and editing of multiple (local) files. 
- Allows the creation of Git Branches and Commits to save different "workspaces"
- Allows to switch between files and between "workspaces" in one click.

![Harmony commit](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3b7qhi30ftbrxup18r6y.png)

It does all that right in your browser. In-memory. Refresh the page to start anew, in another empty repository.

I won't go into how, that's for another post (maybe). 

Here's the [repository](https://github.com/thomscoder/harmony) where there's a video.

Here's the [demo](https://harmonyland.vercel.app).
Bridge the Gap by ChasetheBlack
Published: 2022-09-29 17:54:36

A lot of what is considered a disparity between the children of the wealthy and those less privileged is actually just a lack of exposure and access. This non-profit endeavours to bridge that gap by providing hardware and training to children in less fortunate areas.
Dunoon, and Langa in Cape Town is where we will start and then as many as we can.

[BTGbyCTB](https://www.facebook.com/BTGbyCTB/?_rdc=1&_rdr)
MLOps vs DevOps: What's the Difference?
Tags: mlops, devops, machinelearningoperations
Published: 2022-09-29 17:45:48

**DevOps**
DevOps is a practice where people work in a team to build and deliver software at the best possible speed. DevOps enable software developers(devs) and operations(Ops) teams to fasten up the delivery of Software through collaboration, and in an iterative manner. 

**MLOps**
DevOps is for streamlining software development and then deploying and monitoring them. In MLOps we focus on Machine Learning Operations. So, the guys who are involved in this methodology are data scientists, IT, and DevOps Engineers. It is a useful approach for creating best-in-class machine learning solutions for the end-user.
Yahtzee terminal game in Python
Tags: beginners, python
Published: 2022-09-29 16:53:04

For the final project for the "CS101: Introduction to Programming" course at Codecademy, I have created a single-player, terminal based Yahtzee game. 

Here is a screenshot from the end of a round: 


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/daijs72yxlcewymeqg98.png)

I've used an Object-oriented approach while coding, and plan to do go over it and refactor after discussing with others and getting a bit more experience. I'm sure there are plenty of inefficiencies and non-best practice things in there, but I wanted to get something working just using my knowledge so far and then come back after seeing how other people approach programming the game. It will be interesting to look at various other implementations!

At the moment, a version that is playable for a single round of the game can be found here: 

https://github.com/JoshRees-Haughton/yahtzee

In the near future I plan to implement:

- Being able to play multiple games in a row
- High score saving (global and per player)
- The option to choose between various rulesets for certain aspects of the game before starting
Merge k sorted list
Tags: python, algorithms
Published: 2022-09-29 16:51:24

**Challenge**

You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.

Merge all the linked-lists into one sorted linked-list and return it.

**Example 1:**

```
Input: lists = [[1,4,5],[1,3,4],[2,6]]
Output: [1,1,2,3,4,4,5,6]
Explanation: The linked-lists are:
[
  1->4->5,
  1->3->4,
  2->6
]
merging them into one sorted list:
1->1->2->3->4->4->5->6
```
**Example 2:**

```
Input: lists = []
Output: []
```
**Example 3:**

```
Input: lists = [[]]
Output: []
```
 
**APPROACH**

This would be the first time I would be learning `linked list` so this took quite some time to figure out. However, let's jump right in.

I love this definition of linked list from **freecodecamp**: [Linked Lists](https://www.google.com/amp/s/www.freecodecamp.org/news/introduction-to-linked-lists-in-python/amp/) are a data structure that store data in the form of a chain. The structure of a linked list is such that each piece of data has a connection to the next one (and sometimes the previous data as well). Each element in a linked list is called a node

You can learn more about [Linked lists](https://www.tutorialspoint.com/python_data_structure/python_linked_lists.htm) here

**Aproach**
Having understood links, I rewrote my algorithm to solve the challenge this way:

- Loop through the k `linked-lists` list.


- Append the node element of the linked list to a new array.


- If there are no empty list and list length equals one, sort new array.


- Create a head node from the sorted array: 
this is the first element of the linked list of the next elements of the list would be linked to


- Loop through rest of the sorted array to link the current element to the previous nodes.
Why Learn Gatsby
Tags: gatsby, webdev, beginners
Published: 2022-09-29 16:41:50

With a massive ecosystem of plugins, themes, and starters, Gatsby allows developers to develop and deploy websites in no time. Gatsby is a great way to learn React because it takes away a lot of the burden needed to get going with a React project. Gatsby utilizes web technologies and tools such as Git, JavaScript, and APIs allowing developers to use more time on application code rather than maintenance and optimization. 

Gatsby is a React-based free and open-source framework that helps developers build blazing-fast websites and applications. It offers built-in performance, scalability and security. Developers love this static site generator for its great documentation and using modern tech stack that's future-proof.

Gatsby is a front end framework, meaning it needs a back end to build on top of. Therefore, Node. js is required for development, but not for deployment.This back end is usually a headless CMS, although Gatsby also lets you build from a database, API, or file system. 

Gatsby can be used to build static sites that are Progressive Web Apps, follow the latest web standards, and are optimized to be highly performance. It makes use of the latest and popular technologies including ReactJS, Webpack, GraphQL, modern ES6+ JavaScript and CSS.

Gatsby is the open source, front end framework for React developers that need to build eCommerce sites, marketing sites, blogs, documentation, and any other type of websites.

Gatsby enables developers to build fast, secure, and powerful websites using a React-based framework and innovative data layer that makes integrating different content, APIs, and services into one web experience incredibly simple.

Benefits of using Gatsby for e-commerce sites include the following: Security inherent in static sites. Blazing fast performance when your pages are converted from React into static files. No server component required with Stripe's client-only Checkout.

Gatsby, which is a static site generator, is famous for blogs and documentation websites. But there is no wrong in build full blown React apps with it. In the case of a blog, Gatsby builds a page for every article at the build time and generates a directory which can be hosted directly.

The plugin creates RestApi nodes from REST API sources. You can source multiple REST APIs at once using this plugin to get data from multiple endpoints (from a single or multiple domains).

Gatsby is based on React.js which is a JavaScript library for building User Interfaces using components. It's relatively easy to learn, and if you're able to write solid JavaScript code, you're good to go.

Happy coding!
Admob Native-ads ios integration installation error
Published: 2022-09-29 16:40:28

IOS Native-ads integration package installation Error.
pod 'Google-Mobile-Ads-SDK'
pod 'GoogleMobileAdsMediationFacebook' added it in podfile and. tried both pod install --repo -update / pod install 
also tried vpn to install the package it does't work for me help me guys
Nasce uma estrela: como funciona o programa GitHub Stars?
Tags: braziliandevs, github
Published: 2022-09-29 16:39:03

> 📌 Todo o conteúdo e informação que eu vou passar para vocês hoje foram retirados do próprio site do programa [GitHub Stars](https://stars.github.com/).

## O que é o programa GitHub Stars?

É um programa do GitHub que premia e reconhece pessoas que influenciam, inspiram e educam outras pessoas no mundo da tecnologia, sendo por vídeos, blog, open source e afins. O programa GitHub Stars oferece as pessoas desenvolvedoras uma oportunidade de mostrar seu trabalho, alcançar mais pessoas e moldar o futuro do GitHub.

## O que eu ganho me tornando GitHub Star?

- **Acesso antecipado**: visualizar os recursos e lançamentos do GitHub, compartilhar seus comentários e moldar os produtos do GitHub.
- **Insight calls**: fazer perguntas, compartilhar insights e fazer brainstorming com membros internos da equipe do GitHub durante reuniões exclusivas da Stars.
- **Educação:** continuar aprendendo e expandindo seu alcance.
- **Convites para eventos e palestras**: acesso especial aos eventos do GitHub.
- **Brindes**: brindes exclusivos para si, além de brindes extras do para compartilhar com outras pessoas.
- **Perfil em destaque**: sua própria estrela personalizada para exibir em casa.

## Como me torno GitHub Star?

Temos três passos para isso: 

1. **Nomeação:** no site das stars a comunidade pode indicar pessoas.
2. **Análise**: as stars indicadas são analisadas pela equipe do GitHub.
3. **Filiação**: as stars são convidadas a participar do programa e são anunciadas nas redes sociais.

Você pode nomear qualquer pessoa, mas você não pode nomear a si mesmo.

## Minha jornada para brilhar

> [Saiba mais da minha jornada até a conquista do GitHub Star](https://www.canva.com/design/DAFBzpkEKgI/eaRtRAVE5Fuv-ixt_T14YA/view)
Why Learn NextJS
Tags: nextjs, beginners, webdev
Published: 2022-09-29 16:36:30

Next. js is a JavaScript framework that enables you to build superfast and extremely user-friendly static websites, as well as web applications using React. Next. js is initially a frontend framework for React. In fact, thanks to Automatic Static Optimization, “static” and “dynamic” become one now. Next. js is a fullstack React framework with support for different data fetching strategies. The first one is server-side rendering, where we fetch data on each request.

Next.js is a React framework that gives you building blocks to create web applications. Next. js works very similarly to React, only with some very useful tools that don't come out of the box in React. By framework, we mean Next.js handles the tooling and configuration needed for React, and provides additional structure, features, and optimizations for your application.

Next. js is a popular open-source JavaScript framework for developing server-side rendered React applications. It's simple, lightweight, and efficient, making it an ideal choice for small- to medium-sized projects. In a nutshell, the framework enables you to get up and running with React quickly and easily. 

Next. js solves the SEO problem by server-side rendering pages so Google can index them appropriately. It also provides a way to build isomorphic apps using the same codebase for client-side routing and server-side rendering. This means that each page exists before being rendered by the browser client-side. In other terms, any web crawler can index them all effortlessly and treat them differently based on their content. So, Next. js is inherently an excellent tool to achieve great SEO performance.

The simple fact is that Next. js has become so popular mainly because it solved an age-old issue developers had with JavaScript rendering in the browser itself. By doing a lot of the work on the server side, the overall end user experience is greatly improved – but at the same time, Next. js still allows that CSR.

It's easy to code - compared to React itself and other frameworks working with React, Next. js requires less code. Developers just have to create the page and link to the component in the header, which means less code, better readability, and improved project management. Speed - Applications built with Next.

If you're planning on creating a web application with server-side rendering; If you already have the knowledge about React, but you're looking for more functionalities; Whenever you plan on building a static site; Lastly, if you want to build an MVP and reduce time-to-market, Next JS should be your go-to framework.

You don't need to master React, but you should have at least some React knowledge as they are both built upon React, and the flow of the work is hugely based upon the React way of doing things. Definitely go through the official React tutorial if nothing else before learning Gatsby or Next.

Happy coding!
Industry Thought LEADer
Tags: webdev, beginners, programming, productivity
Published: 2022-09-29 16:33:32

After dissecting Hub spot's article about 10 ways you can establish yourself as an Industry thought leader a person can start pondering about if those are key elements for a great leader. A suggestion that Hub spot should add to their article is one word: Consistency, anyone could perform any of those ways but if they do not uphold their consistent patterns then you cannot lead.

Source:(https://blog.hubspot.com/blog/tabid/6307/bid/22170/6-ways-to-establish-yourself-as-an-industry-thought-leader.aspx?ref=dailydevbytes.com)
Why Learn React
Tags: react, beginners
Published: 2022-09-29 16:32:27

React saves you time and money on development because it's component-based. You can break down an interface into reusable components that allow you to build dynamic user interfaces. 

ReactJS is an indisputably great language for programming web pages and applications, and within that JS spectrum, it is still unchallenged. There are other players in the arena, but professional web app developers would confirm that React still remains on top of others in 2022.

React development has emerged as the future of web creation with its extra versatility and ease. It has a fast learning curve for new developers. If you're not an expert web developer, React can be an easy way to introduce yourself to a lot of HTML, CSS and JS concepts all at the same time.

ReactJS is extremely intuitive to work with and provides interactivity to the layout of any UI. Plus, it enables fast and quality assured application development that in turn saves tome for both - clients and developers.

What makes React such a desirable library to learn is that it doesn't replace HTML. It takes advantage of HTML's popularity and strength as the most popular programming language, by letting you use a very similar syntax to HTML to build interfaces and add dynamic features to it using JavaScript. You will easily grasp the components right away even without guidance from another developer. It is super easy!

Apart from the above trends, there are many reasons implying that ReactJS is potentially the future of web development for example; ReactJS has overtaken jQuery and become the most used web framework by software developers worldwide. It's one of the fastest-growing and most in-demand technologies right now. Even if you don't end up using React for your work, learning front-end concepts and knowing JavaScript at a high level can provide you with many other opportunities.

Happy coding!
VMException while transferring Ether from one Smart contract to other
Published: 2022-09-29 16:31:59



```
`pragma solidity 0.5.16;
contract SC1 {
    address owner;
    constructor() public {
        owner = msg.sender;
    }
    function transferTo(uint amount, address payable dest ) public {
        require(tx.origin == owner);
        dest.transfer(amount);
    }
    function () external payable{
    }
}`
```
==

```
`pragma solidity ^0.5.16;
interface SC1 {  
   function transferTo(uint amount, address payable to   ) external;
}
contract SC2{

    uint public  count;
    address owner;
    constructor() public {
        owner = msg.sender;
    }
    function() external payable  { 
      count++; 
      if (count < 2 ) 
         TxUserWallet(msg.sender).transferTo(msg.sender.balance, address(this));
      
   }
}
```

truffle script


```
`var assert = require('assert');
const path = require("path");
const fs = require("fs");


module.exports = async function(callback) {
  try {
     let arg1 = ""
     let arg2  = ""
     let  amount = '6'
     const accounts = await web3.eth.getAccounts();
     const acc2 = accounts[2];
     transferFuncName= "transferTo"
     const vic= artifacts.require("SC1");
     const att= artifacts.require("SC2");
     const vicobj = await vic.new();
     const attobj = await att.new();
     result1 = await web3.eth.sendTransaction({to:vicobj.address, from:acc2, value: web3.utils.toWei(‘11’)})
    
     arg2 =  attobj.address
     arg1 = web3.utils.toWei(amount,"ether")
     result2 = await vicobj[transferFuncName](arg1, arg2, {from:accounts[0]})
    }
 catch(error) {
    console.log(error)
  }

  callback()
}

```

Following is the error message:

> Using network 'development'.
> { Error: Returned error: VM Exception while processing transaction: revert
>     at module.exports (/home/zulfi/Truffle_programs/js_search_opcode_js/executingFunc.js:23:46)
>     at process._tickCallback (internal/process/next_tick.js:68:7)
>   hijackedStack:
>    'Error: Returned error: VM Exception while processing transaction: revert\n    at Object.ErrorResponse (/home/zulfi/.nvm/versions/node/v10.23.3/lib/node_modules/truffle/build/webpack:/node_modules/web3-core-helpers/src/errors.js:29:1)\n    at /home/zulfi/.nvm/versions/node/v10.23.3/lib/node_modules/truffle/build/webpack:/node_modules/web3/node_modules/web3-core-requestmanager/src/index.js:170:1\n    at /home/zulfi/.nvm/versions/node/v10.23.3/lib/node_modules/truffle/build/webpack:/packages/provider/wrapper.js:107:1\n  

Somebody please guide me.

Zulfi.
Why Learn JavaScript
Tags: javascript, webdev, beginners
Published: 2022-09-29 16:28:25

When it comes to programming languages, there is an embarrassment of riches, which in turn can cause mental gridlock. There’s Python, Java, JavaScript, C/CPP, PHP, Swift, C#, Ruby, Objective-C, and SQL, and that’s not even the full list....

JavaScript supports valuable skills such as object-oriented, functional, and imperative styles of programming. It first appeared in 1995. JavaScript makes web pages more dynamic and user-friendly so that they respond to visitors’ actions.

1. It’s the most popular programming language
2. JavaScript also exists outside of the internet
3. JavaScript is ideal for beginners since it's easy to learn
4. You can create visual effects
5. JavaScript is versatile
6. It's a valuable tool for game designers
7. The career potential is skyrocketing
8. It works in the browser
9. There's a big community
10. There are a lot of shortcuts, when you’re ready to take them.

Once you've mastered it, the possibilities are endless: you can code on the client-side using Angular and on the server-side using Node.js. You can also develop web, mobile, and desktop apps using React, React Native, and Electron, and you can even get involved in machine learning. 

If you want to become a frontend developer, JavaScript is a prerequisite. However, that's not the only career path open to you as a JavaScript expert. Mastering this key programming language could see you go on to work in full-stack development, games development, information security software engineering, machine learning, and artificial intelligence—to name just a few!

You should start with plain old vanilla JavaScript first. The best way to start learning JavaScript is to get hands-on.

Happy coding!