Post(s) tagged Array
Javascript sort an array based on another array
Data array
var dataArray = [
{ name: 'Alberta Owen', id: 1 },
{ name: 'Jimmy Murphy', id: 2 },
{ name: 'Jerald Roberson', id: 3 },
{ name: 'Roosevelt Douglas', id: 4 },
{ name: 'Mark Ramsey', id: 5 }
]
Sort array
var sortArray = ['Mark Ramsey', 'Jimmy Murphy', 'Alberta Owen'];
Sorting
dataArray.sort((a, b) => sortArray.indexOf(a) - sortArray.indexOf(b));
Posted on February 10, 2022
Import JSON array from local file to Typescript array
The sample JSON file content (data.json):
[
{
"FirstName": "Joe",
"UserId": 1
},
{
"FirstName": "Jack",
"UserId": 2
}
]
Next, add appropriate resolveJsonModule
entry to tsconfig.json
entry
{
"compilerOptions": {
"esModuleInterop": true
"resolveJsonModule": true
}
}
Finally, import the data and access it using the below code.
import data from './data.json';
interface Person{
FirstName: string,
UserId: number,
}
const userArray:User[] = data as User[];
Posted on February 27, 2022