Search⌘ K

Exercise: String Slicing

Explore how to apply the slice method on strings and arrays, and understand the use of sorting with localCompare in JavaScript. This lesson helps you practice sorting string rows while preserving headers, improving your skills in string manipulation and array handling techniques.

We'll cover the following...

Sort the rows given below based on their titles. Make sure you exclude the header row.

Hint: the slice method works in the same way on arrays as on strings.

Solution

First, we get rid of the first row:

Javascript (babel-node)
const data = `
Title,Author,Publication Date,Publisher
ES6 in Practice,Zsolt Nagy,2017,Self-published
The Developer's Edge,Zsolt Nagy,2016,Self-published
Regex Quick Syntax Reference,Zsolt Nagy,2018,Apress
The Charismatic Coder,Zsolt Nagy,2018,Self-published
Deep Dive into Functional JavaScript,Zsolt Nagy,2017,PacktPub
Implementing and Testing Applications using Functional JavaScript,Zsolt Nagy,2017,PacktPub
Mastering Functional JavaScript Libraries,Zsolt Nagy,2017,PacktPub
Beginning Modern JavaScript Development with Microservices WebRTC and React,Zsolt Nagy,2017,PacktPub
Beginning ASP.NET,Zsolt Nagy,2017,PacktPub
Become the CSS Hero of Your Office with CSS Architecture,Zsolt Nagy,2017,SitePoint
Setting Up and Kick Starting TypeScript,Zsolt Nagy,2017,SitePoint
`;
const result = data.trim().split('\n').map( row => row.split(',') );
const dataRows = result.slice( 1 );
console.log(dataRows)

We have to sort the data rows using the array sort ...