Skip to content

Lists and Keys React

Bryan C Guner edited this page May 11, 2021 · 1 revision

First, let’s review how you transform lists in JavaScript.

Given the code below, we use the map() function to take an array of numbers and double their values. We assign the new array returned by map() to the variable doubled and log it:

const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map((number) => number * 2);console.log(doubled);

This code logs [2, 4, 6, 8, 10] to the console.

In React, transforming arrays into lists of elements is nearly identical.

Rendering Multiple Components

You can build collections of elements and include them in JSX using curly braces {}.

Below, we loop through the numbers array using the JavaScript map() function. We return a <li> element for each item. Finally, we assign the resulting array of elements to listItems:

const numbers = [1, 2, 3, 4, 5];
const listItems = numbers.map((number) =>  <li>{number}</li>);

We include the entire listItems array inside a <ul> element, and render it to the DOM:

ReactDOM.render(
  <ul>{listItems}</ul>,  document.getElementById('root')
);

Try it on CodePen

This code displays a bullet list of numbers between 1 and 5.

Basic List Component

Usually you would render lists inside a component.

We can refactor the previous example into a component that accepts an array of numbers and outputs a list of elements.

function NumberList(props) {
  const numbers = props.numbers;
  const listItems = numbers.map((number) =>    <li>{number}</li>  );  return (
    <ul>{listItems}</ul>  );
}

const numbers = [1, 2, 3, 4, 5];
ReactDOM.render(
  <NumberList numbers={numbers} />,  document.getElementById('root')
);

When you run this code, you’ll be given a warning that a key should be provided for list items. A “key” is a special string attribute you need to include when creating lists of elements. We’ll discuss why it’s important in the next section.

Let’s assign a key to our list items inside numbers.map() and fix the missing key issue.

function NumberList(props) {
  const numbers = props.numbers;
  const listItems = numbers.map((number) =>
    <li key={number.toString()}>      {number}
    </li>
  );
  return (
    <ul>{listItems}</ul>
  );
}

const numbers = [1, 2, 3, 4, 5];
ReactDOM.render(
  <NumberList numbers={numbers} />,
  document.getElementById('root')
);

Try it on CodePen

Keys

Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity:

const numbers = [1, 2, 3, 4, 5];
const listItems = numbers.map((number) =>
  <li key={number.toString()}>    {number}
  </li>
);

The best way to pick a key is to use a string that uniquely identifies a list item among its siblings. Most often you would use IDs from your data as keys:

const todoItems = todos.map((todo) =>
  <li key={todo.id}>    {todo.text}
  </li>
);

When you don’t have stable IDs for rendered items, you may use the item index as a key as a last resort:

const todoItems = todos.map((todo, index) =>
    <li key={index}>    {todo.text}
  </li>
);

We don’t recommend using indexes for keys if the order of items may change. This can negatively impact performance and may cause issues with component state. Check out Robin Pokorny’s article for an in-depth explanation on the negative impacts of using an index as a key. If you choose not to assign an explicit key to list items then React will default to using indexes as keys.

Here is an in-depth explanation about why keys are necessary if you’re interested in learning more.

Keys only make sense in the context of the surrounding array.

For example, if you extract a ListItem component, you should keep the key on the <ListItem /> elements in the array rather than on the <li> element in the ListItem itself.

Example: Incorrect Key Usage

function ListItem(props) {
  const value = props.value;
  return (
        <li key={value.toString()}>      {value}
    </li>
  );
}

function NumberList(props) {
  const numbers = props.numbers;
  const listItems = numbers.map((number) =>
        <ListItem value={number} />  );
  return (
    <ul>
      {listItems}
    </ul>
  );
}

const numbers = [1, 2, 3, 4, 5];
ReactDOM.render(
  <NumberList numbers={numbers} />,
  document.getElementById('root')
);

Example: Correct Key Usage

function ListItem(props) {
    return <li>{props.value}</li>;}

function NumberList(props) {
  const numbers = props.numbers;
  const listItems = numbers.map((number) =>
        <ListItem key={number.toString()} value={number} />  );
  return (
    <ul>
      {listItems}
    </ul>
  );
}

const numbers = [1, 2, 3, 4, 5];
ReactDOM.render(
  <NumberList numbers={numbers} />,
  document.getElementById('root')
);

Try it on CodePen

A good rule of thumb is that elements inside the map() call need keys.

Keys Must Only Be Unique Among Siblings

Keys used within arrays should be unique among their siblings. However they don’t need to be globally unique. We can use the same keys when we produce two different arrays:

function Blog(props) {
  const sidebar = (    <ul>
      {props.posts.map((post) =>
        <li key={post.id}>          {post.title}
        </li>
      )}
    </ul>
  );
  const content = props.posts.map((post) =>    <div key={post.id}>      <h3>{post.title}</h3>
      <p>{post.content}</p>
    </div>
  );
  return (
    <div>
      {sidebar}      <hr />
      {content}    </div>
  );
}

const posts = [
  {id: 1, title: 'Hello World', content: 'Welcome to learning React!'},
  {id: 2, title: 'Installation', content: 'You can install React from npm.'}
];
ReactDOM.render(
  <Blog posts={posts} />,
  document.getElementById('root')
);

Try it on CodePen

Keys serve as a hint to React but they don’t get passed to your components. If you need the same value in your component, pass it explicitly as a prop with a different name:

const content = posts.map((post) =>
  <Post
    key={post.id}    id={post.id}    title={post.title} />
);

With the example above, the Post component can read props.id, but not props.key.

Embedding map() in JSX

In the examples above we declared a separate listItems variable and included it in JSX:

function NumberList(props) {
  const numbers = props.numbers;
  const listItems = numbers.map((number) =>    <ListItem key={number.toString()}              value={number} />  );  return (
    <ul>
      {listItems}
    </ul>
  );
}

JSX allows embedding any expression in curly braces so we could inline the map() result:

function NumberList(props) {
  const numbers = props.numbers;
  return (
    <ul>
      {numbers.map((number) =>        <ListItem key={number.toString()}                  value={number} />      )}    </ul>
  );
}

Try it on CodePen

Sometimes this results in clearer code, but this style can also be abused. Like in JavaScript, it is up to you to decide whether it is worth extracting a variable for readability. Keep in mind that if the map() body is too nested, it might be a good time to extract a component.

Hi 👋, I'm Bryan


Profile views



Refresh the page for a new joke!

-----------------------------------------------------

  bgoonz

bgoonz

trophy

Top Langs

Languages


                                                                                                                                                                                                                                        |

| Libraries |

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |

| Frameworks |

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |

| Databases |

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |

| Testing |

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |

| Other |




|


➤ Current Projects:

ReadMe Card ReadMe Card ReadMe Card ReadMe Card

-----------------------------------------------------

Email

-----------------------------------------------------

Phone


➤ Connect with me:

emailfacebooktwitteryoutubeinstagrampinterestlinkedin mediumspotify

-----------------------------------------------------

Blog:

I write articles for:

  • CodeX

  • Analytics Vidhya

  • Star Gazers

  • JavaScript in Plain English

  • Geek Culture

  • Level Up Coding

  • Bryan C Guner's DEV Community Profile

![medium](./medium. PNG)

-----------------------------------------------------

About Me

-----------------------------------------------------

![skills](./skills. PNG)

-----------------------------------------------------

Awesome Made With Love

forthebadgeforthebadge

Website shields.ioAsk Me Anything !GitterPyPI license

MaintenanceAnalyticsOpen Source Love Bash Shell

GitHub followers

JavaScript

React Redux

HTML5 CSS3 Sass

Express NodejsPython Bootstrap

Docker MySQL PostgresQL Git Ruby Material-UI

Languages and Tools:

arduino aws azure babel bash bootstrap cplusplus css3 d3js docker elasticsearch ember express firebase gatsby gcp git heroku html5 javascript jekyll linux matlab mocha mongodb nextjs nodejs photoshop postgresql postman pug puppeteer python react reactnative typescript vagrant webpack xd zapier

A passionate Web Developer, Electrical Engineer, Musician & Producer

i really like music 🎧

What's the most useful business-related book you've ever read?

A Random Walk Down Wall Street

What's your favorite non-business book?

Hitchhiker's Guide To The Galaxy

If money were not an issue, what would you be doing right now?

Designing recording software/hardware and using it

What words of advice would you give your younger self?

Try harder and listen to your parents more (the latter bit of advice would be almost certain to fall on deaf ears lol)

What's the most creative thing you've ever done?

I built a platform that listens to a guitarist's performance and automatically triggers guitar effects at the appropriate time in the song.

Which founders or startups do you most admire?

Is it to basic to say Tesla... I know they're prevalent now but I've been an avid fan since as early as 2012.

What's your super power?

Having really good ideas and forgetting them moments later.

What's the best way for people to get in touch with you?

A text

What aspects of your work are you most passionate about?

Creating things that change my every day life.

What was the most impactful class you took in school?

Modern Physics... almost changed my major after that class... but at the end of the day engineering was a much more fiscally secure avenue.

What's something you wish you had done years earlier?

Learned to code ... and sing

What words of wisdom do you live by?

*Disclaimer: The following wisdom is very cliche ... but... "Be the change that you wish to see in the world."

― Mahatma Gandhi

🤖 My Programming Stats:

bgoonz's wakatime stats

![waka1](https://github.com/bgoonz/bgoonz/blob/master/langs. PNG)

![waka2](https://github.com/bgoonz/bgoonz/blob/master/waka. PNG)

See More

wakatime

github-resume

Resume

➤ Technical Skills­­­

Programming** Languages:** JavaScript ES-6, NodeJS, React, HTML5, CSS3, SCSS, Bash Shell, Excel, SQL, NoSQL, MATLAB, Python, C++
Databases: PostgreSQL, MongoDB
Cloud: Docker, AWS, Google App Engine, Netlify, Digital Ocean, Heroku, Azure Cloud Services
OS: Linux, Windows (WSL), IOS
Agile: GitHub, BitBucket, Jira, Confluence
IDEs: VSCode, Visual Studio, Atom, Code Blocks, Sublime Text 3, Brackets

-----------------------------------------------------

➤ Experience

Relational Concepts: Hallandale Beach, FL March 2020 - Present
Front End Web Developer
  • Responsible for front-end development for a custom real estate application which provides sophisticated and fully customizable filtering to allow investors and real estate professionals to narrow in on exact search targets.
  • Designed mock-up screens, wireframes, and workflows for intuitive user experience.
  • Migrated existing multi-page user experience into singular page interfaces using React components.
  • Participated in every stage of the design from conception through development and iterative improvement.
  • Produced user stories and internal documentation for future site development and maintenance.
  • Implemented modern frameworks including Bootstrap and Font-Awesome to give the site an aesthetic overhaul.
  • Managed all test deployments using a combination of Digital Ocean and Netlify.
  • Produced unit tests using a combination of Mocha and Chai.
  • Injected Google Analytics to capture pertinent usage data to produce an insightful dashboard experience.
Environment: JavaScript, JQuery, React, HTML5 & CSS, Bootstrap, DOJO, Google Cloud, Bash Script
Cembre: Edison, NJ Nov 2019 – Mar 2020
Product Development Engineer
  • Converted client' s product needs into technical specs to be sent to the development team in Italy.
  • Reorganized internal file server structure.
  • Conducted remote / in person system integration and product demonstrations.
  • Presided over internal and end user software trainings in addition to producing the corresponding documentation.
  • Served as the primary point of contact for troubleshooting railroad hardware and software in the North America.
Environment: Excel, AutoCAD, PowerPoint, Word

-----------------------------------------------------

➤ Education

**B. S. Electrical Engineering, TCNJ, ** Ewing NJ 2014 – 2019

Capstone Project – Team Lead

  • Successfully completed and delivered a platform to digitize a guitar signal and perform filtering before executing frequency & time domain analysis to track a current performance against prerecorded performance.
  • Implemented the Dynamic Time Warping algorithm in C++ and Python to autonomously activate or adjust guitar effect at multiple pre-designated section of performance.
Environment: C++, Python, MATLAB, PureData
My Projects
<tr>
  <th>Project Name</th>
  <th>Skills used</th>
  <th>Description</th>
</tr>
<tr>
  <td><a href='https://web-dev-resource-hub.netlify.app/'>Web-Dev-Resource-Hub (blog)</a></td>
  <td>Html, Css, javascript, Python, jQuery,  React,  FireBase,  AWS S3,  Netlify,  Heroku,  NodeJS,  PostgreSQL,  C++,  Web Audio API</td>
  <td>My blog site contains my resource sharing and blog site ... centered mostly on web development and just a bit of audio production / generally nerdy things I find interesting.</td>
</tr>
   <tr>
  <td><a href='https://project-showcase-bgoonz.netlify.app/'>Dynamic Guitar Effects Triggering Using A Modified Dynamic Time Warping Algorithm</a></td>
  <td>C, C++, Python, Java, Pure Data, Matlab</td>
  <td>Successfully completed and delivered a platform to digitize a guitar signal and perform filtering before executing frequency & time domain analysis to track a current performance against prerecorded performance.Implemented the Dynamic Time Warping algorithm in C++ and Python to autonomously activate or adjust guitar effect at multiple pre-designated section of performance.</td>
</tr>
<tr>
  <td><a href="https://trusting-dijkstra-4d3b17.netlify.app/">Data Structures & Algorithms Interactive Learning Site</a></td>
  <td>HTML, CSS, Javascript,  Python,  Java,  jQuery,  Repl.it-Database API</td>
  <td>A interactive and comprehensive guide and learning tool for DataStructures and Algorithms ... concentrated on JS but with some examples in Python,  C++ and Java as well</td>
</tr>
<tr>
  <td><a href='https://mihirbegmusic.netlify.app/'>MihirBeg.com</a></td>
  <td>Html, Css, Javascript,  Bootstrap,  FontAwesome,  jQuery</td>
  <td>A responsive and mobile friendly content promotion site for an Audio Engineer to engage with fans and potential clients</td>
</tr>
<tr>
  <td><a href='https://tetris42.netlify.app/'>Tetris-JS</a></td>
  <td>Html, Css, Javascript</td>
  <td>The classic game of tetris implemented in plain javascipt and styled with a retro-futureistic theme</td>
</tr>
<tr>
  <td><a href="https://githtmlpreview.netlify.app/">Git Html Preview Tool</a></td>
  <td>Git,  Javascript,  CSS3,  HTML5,  Bootstrap,  BitBucket</td>
  <td>Loads HTML using CORS proxy,  then process all links,  frames,  scripts and styles,  and load each of them using CORS proxy,  so they can be evaluated by the browser.</td>
</tr>
<tr>
  <td><a href='https://project-showcase-bgoonz.netlify.app/'>Mini Project Showcase</a></td>
  <td>HTML, HTML5, CSS, CSS3, Javascript, jQuery</td>
  <td>add songs and play music, it also uses to store data in  INDEXEDB Database by which we can play songs, if we not clear the catch then song will remain stored in database.</td>
</tr>



Portfolio:



hr-line


React Repo:

React Repo


Foo

---
hr-line

Edit magical-stallman-ov0d1

hr-line

➤ Codepens (mostly embeded animations)

-----------------------------------------------------

➤ Weekly-Quick-Snips:


Snippet of the Day:

replaceAll

the method string.replaceAll(search, replaceWith) replaces all appearances of search string with replaceWith.

const str = 'this is a JSsnippets example';

const updatedStr = str.replace('example', 'snippet'); // 'this is a  JSsnippets snippet'

The tricky part is that replace method replaces only the very first match of the substring we have passed:

    const str = 'this is a JSsnippets example and examples are great';

const updatedStr = str.replace('example', 'snippet'); //'this is a JSsnippets snippet and examples are great'

In order to go through this, we need to use a global regexp instead:

    const str = 'this is a JSsnippets example and examples are great';

const updatedStr = str.replace(/example/g, 'snippet'); //'this is a JSsnippets snippet and snippets are greatr'

but now we have new friend in town, replaceAll

const str = 'this is a JSsnippets example and examples are great';

const updatedStr = str.replaceAll('example', 'snippet'); //'this is a JSsnippets snippet and snippets are greatr'

Fibonacci in Python:

def fib_iter(n):
    if n == 0:
        return 0
    if n == 1:
        return 1
    p0 = 0
    p1 = 1
    for i in range(n-1):
        next_val = p0 + p1
        p0 = p1
        p1 = next_val
    return next_val
for i in range(10):
    print(f'{i}: {fib_iter(i)}')

Yesterday's Snippet of the day:


def quicksort(l):
    # One of our base cases is an empty list or list with one element
    if len(l) == 0 or len(l) == 1:
        return l
    # If we have a left list, a pivot point and a right list...
    # assigns the return values of the partition() function
    left, pivot, right = partition(l) 
    # Our sorted list looks like left + pivot + right, but sorted.
    # Pivot has to be in brackets to be a list, so python can concatenate all the elements to a single list
    return quicksort(left) + [pivot] + quicksort(right)

print(quicksort([]))

print(quicksort([1]))

print(quicksort([1,2]))

print(quicksort([2,1]))

print(quicksort([2,2]))

print(quicksort([5,3,9,4,8,1,7]))

print(quicksort([1,2,3,4,5,6,7]))

print(quicksort([9,8,7,6,5,4,3,2,1]))

See Older Snippets!

This Week's snippets:


will replace any spaces in file names with an underscore!

 for file in *; do mv "$file" `echo $file | tr ' ' '_'` ; done
  ## TAKING IT A STEP FURTHER:
 # Let's do it recursivley:
  function RecurseDirs ()
{
    oldIFS=$IFS
    IFS=$'\n'
    for f in "$@"
    do
  # YOUR CODE HERE!

[![-----------------------------------------------------](https://raw.githubusercontent.com/andreasbm/readme/master/assets/lines/colored.png)]

   for file in *; do mv "$file" `echo $file | tr ' ' '_'` ; done
        if [[ -d "${f}" ]]; then
            cd "${f}"
            RecurseDirs $(ls -1 ".")
            cd ..
        fi
    done
    IFS=$oldIFS
}
RecurseDirs "./"
  

Copy to clipboard jQuerry

Language: Javascript/Jquery

In combination with the script tag : <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> , this snippet will add a copy to clipboard button to all of your embedded blocks.

$(document).ready(function() {
    $('code, pre').append('<span class="command-copy" ><i class="fa fa-clipboard" aria-hidden="true"></i></span>');

    $('code span.command-copy').click(function(e) {
        var text = $(this).parent().text().trim(); //.text();
        var copyHex = document.createElement('input');
        copyHex.value = text
        document.body.appendChild(copyHex);
        copyHex.select();
        document.execCommand('copy');
        console.log(copyHex.value)
        document.body.removeChild(copyHex);
    });

    $('pre span.command-copy').click(function(e) {
        var text = $(this).parent().text().trim();
        var copyHex = document.createElement('input');
        copyHex.value = text
        document.body.appendChild(copyHex);
        copyHex.select();
        document.execCommand('copy');
        console.log(copyHex.value)
        document.body.removeChild(copyHex);
    });
})

Append Files in PWD

//APPEND-DIR.js
const fs = require('fs');
let cat = require('child_process').execSync('cat *').toString('UTF-8');
fs.writeFile('output.md', cat, (err) => {
    if (err) throw err;
});

doesUserFrequentStarbucks.js

const isAppleDevice = /Mac|iPod|iPhone|iPad/.test(navigator.platform);
console.log(isAppleDevice);
// Result: will return true if user is on an Apple device

arr-intersection.js

/*
 function named intersection(firstArr) that takes in an array and
returns a function. 
When the function returned by intersection is invoked
passing in an array (secondArr) it returns a new array containing the elements
common to both firstArr and secondArr.
*/
function intersection(firstArr) {
    return (secondArr) => {
        let common = [];
        for (let i = 0; i < firstArr.length; i++) {
            let el = firstArr[i];
            if (secondArr.indexOf(el) > -1) {
                common.push(el);
            }
        }
        return common;
    };
}
let abc = intersection(["a", "b", "c"]); // returns a function
console.log(abc(["b", "d", "c"])); // returns [ 'b', 'c' ]

let fame = intersection(["f", "a", "m", "e"]); // returns a function
console.log(fame(["a", "f", "z", "b"])); // returns [ 'f', 'a' ]

arr-of-cum-partial-sums.js

/*
First is recurSum(arr, start) which returns the sum of the elements of arr from the index start till the very end.
Second is partrecurSum() that recursively concatenates the required sum into an array and when we reach the end of the array, it returns the concatenated array.
*/
//arr.length -1 = 5 
//                   arr   [    1,    7,    12,   6,    5,    10   ]
//                   ind   [    0     1     2     3     4      5   ]
//                              ↟                              ↟
//                            start                           end

function recurSum(arr, start = 0, sum = 0) {
    if (start < arr.length) {
        return recurSum(arr, start + 1, sum + arr[start]);
    };

    return sum;
}

function rPartSumsArr(arr, partSum = [], start = 0, end = arr.length - 1) {
    if (start <= end) {
        return rPartSumsArr(arr, partSum.concat(recurSum(arr, start)), ++start, end);
    };
    return partSum.reverse();
}

console.log('------------------------------------------------rPartSumArr------------------------------------------------')
console.log('rPartSumsArr(arr)=[ 1, 1, 5, 2, 6, 10 ]: ', rPartSumsArr(arr));
console.log('rPartSumsArr(arr1)=[ 1, 7, 12, 6, 5, 10 ]: ', rPartSumsArr(arr1));
console.log('------------------------------------------------rPartSumArr------------------------------------------------')
/*
------------------------------------------------rPartSumArr------------------------------------------------
rPartSumsArr(arr)=[ 1, 1, 5, 2, 6, 10 ]:  [ 10, 16, 18, 23, 24, 25 ]
rPartSumsArr(arr1)=[ 1, 7, 12, 6, 5, 10 ]:  [ 10, 15, 21, 33, 40, 41 ]
------------------------------------------------rPartSumArr------------------------------------------------
*/

camel2Kabab.js

function camelToKebab(value) {
    return value.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase();
}

camelCase.js

function camel(str) {
    return str.replace(/(?:^\w|[A-Z]|\b\w|\s+)/g, function(match, index) {
        if (+match === 0) return ""; // or if (/\s+/.test(match)) for white spaces
        return index === 0 ? match.toLowerCase() : match.toUpperCase();
    });
}

concatLinkedLists.js

function addTwoNumbers(l1, l2) {
    let result = new ListNode(0)
    let currentNode = result
    let carryOver = 0
    while (l1 != null || l2 != null) {
        let v1 = 0
        let v2 = 0
        if (l1 != null) v1 = l1.val
        if (l2 != null) v2 = l2.val

        let sum = v1 + v2 + carryOver
        carryOver = Math.floor(sum / 10)
        sum = sum % 10
        currentNode.next = new ListNode(sum)

        currentNode = currentNode.next
        if (l1 != null) l1 = l1.next
        if (l2 != null) l2 = l2.next
    }

    if (carryOver > 0) {
        currentNode.next = new ListNode(carryOver)
    }

    return result.next
};

fast-is-alpha-numeric.js

//Function to test if a character is alpha numeric that is faster than a regular
//expression in JavaScript

let isAlphaNumeric = (char) => {
    char = char.toString();
    let id = char.charCodeAt(0);
    if (
        !(id > 47 && id < 58) && // if not numeric(0-9)
        !(id > 64 && id < 91) && // if not letter(A-Z)
        !(id > 96 && id < 123) // if not letter(a-z)
    ) {
        return false;
    }
    return true;
};

console.log(isAlphaNumeric("A")); //true
console.log(isAlphaNumeric(2)); //true
console.log(isAlphaNumeric("z")); //true
console.log(isAlphaNumeric(" ")); //false
console.log(isAlphaNumeric("!")); //false

find-n-replace.js

function replaceWords(str, before, after) {
    if (/^[A-Z]/.test(before)) {
        after = after[0].toUpperCase() + after.substring(1)
    } else {
        after = after[0].toLowerCase() + after.substring(1)
    }
    return str.replace(before, after)
}
console.log(replaceWords("Let us go to the store", "store", "mall")) //"Let us go to the mall"
console.log(replaceWords("He is Sleeping on the couch", "Sleeping", "sitting")) //"He is Sitting on the couch"
console.log(replaceWords("His name is Tom", "Tom", "john"))
//"His name is John"

flatten-arr.js

/*Simple Function to flatten an array into a single layer */
const flatten = (array) =>
    array.reduce(
        (accum, ele) => accum.concat(Array.isArray(ele) ? flatten(ele) : ele),
        []
    );

isWeekDay.js

const isWeekday = (date) => date.getDay() % 6 !== 0;
console.log(isWeekday(new Date(2021, 0, 11)));
// Result: true (Monday)
console.log(isWeekday(new Date(2021, 0, 10)));
// Result: false (Sunday)

longest-common-prefix.js

function longestCommonPrefix(strs) {
    let prefix = ''
    if (strs.length === 0) return prefix
    for (let i = 0; i < strs[0].length; i++) {
        const character = strs[0][i]
        for (let j = 0; j < strs.length; j++) {
            if (strs[j][i] !== character) return prefix
        }
        prefix = prefix + character
    }
    return prefix
}

-----------------------------------------------------

➤ Github Gists

list-of-my-websites


daft

Clone this wiki locally