Get a specific item length in array object [nodejs] - arrays

I want to get the length of an array that match the value specified by the condition.
var school = {
student : {
name: Json,
class: 0,
type: male,
average: B+
},
student : {
name: Afrado,
class: 0,
type: male,
average: C+
},
student : {
name: Emily,
class: 1,
type: female,
average: A+
}
};
I'd like to know the lengh of class "0"
but I don't know how to resolve this case?
In this case I can get the length of "2" for my results.
Have a nice day~ :)

Your array is not structured properly, what you need to do is to filter and get the length of the filtered items.
var school = [
{
name: "Json",
class: 0,
type: "male",
average: "B+"
},
{
name: "Afrado",
class: 0,
type: "male",
average: "C+"
},
{
name: "Emily",
class: "1",
type: "female",
average: "A+"
}
];
console.log(school.filter(student => student.class === 0).length);

You can use the reduce function to avoid creating a temporary array with filter.
console.log(school.reduce((count, student) => student.class === 0 ? ++count : count, 0));

you can also use this way:
var school = [
{
name: "Json",
class: 0,
type: "male",
average: "B+"
},
{
name: "Afrado",
class: 0,
type: "male",
average: "C+"
},
{
name: "Emily",
class: "1",
type: "female",
average: "A+"
}
];
function search(className, myArray){
var countClass = 0;
for (var i=0; i < myArray.length; i++) {
if (myArray[i].class === className) {
countClass++;
}
}
return countClass;
}
function searchForeach(className, myArray){
var countClass = 0;
myArray.forEach((item) => {
if (item.class === className) {
countClass++;
}
});
return countClass;
}
function searchFind(className, myArray){
var countClass = 0;
myArray.find((item, index) => {
if (item.class === className) {
countClass++;
}
});
return countClass;
}
console.log(search(0, school));
console.log(searchForeach("1", school));
console.log(searchFind(0, school));
second way use find:

Related

How to Search or Compare values out of array of Objects in Javascript and return based on input

I have simply iterated through an array of objects. But I have no clue how I should compare the previous object values and display data along with current data. as shown in the image.
My Half solutions:
const dataSet = [{
categoryId: 100,
parentCategoryId: -1,
name: "Business",
keyword: "Money",
},
{
categoryId: 200,
parentCategoryId: -1,
name: "Tutoring",
keyword: "Teaching",
},
{
categoryId: 101,
parentCategoryId: 100,
name: "Accounting",
keyword: "Taxes",
},
{
categoryId: 102,
parentCategoryId: 100,
name: "Taxation",
keyword: "",
},
{
categoryId: 201,
parentCategoryId: 200,
name: "Computer",
keyword: "",
},
{
categoryId: 103,
parentCategoryId: 101,
name: "Corporate Tax",
keyword: "",
},
{
categoryId: 202,
parentCategoryId: 201,
name: "Operating System",
keyword: "",
},
{
categoryId: 109,
parentCategoryId: 101,
name: "Small Business Tax",
keyword: "",
}
]
function solution(X) {
// search your keyword
dataSet.map((item)=>{
console.log("Item List: ", item);
if (X === item.categoryId){
const displayData = `\n\t ParentCategoryId : ${item.parentCategoryId} \n\t Name : ${item.name} \n\t Kewords : ${item.keyword}`;
try{
if(displayData) {
console.log("Your Searched Data:", displayData);
}
}catch (e) {
return console.log ("error:", e);
}
}
})
}
solution(201);
Below method will solve your problem.
function solution(cId){
let result = null;
const getParentNode = function(parentId){
const parentNode = dataSet.find(elm => elm.categoryId === parentId);
if(parentNode && parentNode.keyword === ""){
return getParentNode(parentNode.parentCategoryId);
}
return parentNode;
}
for(let i=0; i<dataSet.length; i++){
if(dataSet[i].categoryId === cId){
if(dataSet[i].keyword === "")
result = {...dataSet[i], keyword: getParentNode(dataSet[i].parentCategoryId).keyword};
else
result = dataSet[i];
break;
}
}
return result;
}
This may probably help you!
var result = result1.filter(function (o1) {
return result2.some(function (o2) {
return o1.id === o2.id; // return the ones with equal id
});
});
// if you want to be more clever...
let result = result1.filter(o1 => result2.some(o2 => o1.id === o2.id));

How can I change TS object array format?

Array which I want change
I have got this array in TypeScript, I want it change as bellow.
list = [{id : 1, name : bus, active : 1}, {id : 2, name : car}]
Can anyone help me?
You can map the input and reduce each element to an object.
const list = [
[{ id: 1 }, { name: 'bus' }, { active: 1 }],
[{ id: 2 }, { name: 'car' }],
];
const result = list.map((el) => {
return el.reduce((acc, curr) => {
return { ...acc, ...curr };
}, {});
});
console.log(result);

Typescript: print keys/values of objects that contains arrays (no forEach)

i'm trying to extract values from an object that contains arrays.
Here's how the object look like:
export const myBookList: Row[] =
[
{
bookInfo: [
{
title: "The jungle book",
isbn: "42398486965239671234",
Author: "Rudyard Kipling"
},
{
title: "20,000 Leagues Under the Sea",
isbn: "42234486234239675678",
Author: "Jules Verne"
},
{
title: "The Call of the Wild",
isbn: "4239848696523967670",
Author: "Jack London"
}
],
value: [],
id: 0
},
{
bookInfo: [
{
title: "The jungle book 2",
isbn: "327865923874659276",
Author: "Rudyard Kipling"
},
{
title: "20,000 Leagues Under the Sea 2",
isbn: "269587649587264675",
Author: "Jules Verne"
},
{
title: "The Call of the Wild",
isbn: "2378687827584758765",
Author: "Rudyard Kipling"
}
],
value: [],
id: 1
}
];
I would like to go through all the keys and values of the object (especially the keys/values in the array bookInfo) and when a key that match the passed string parameter "myKey" is found, i would like to return the key value.
The code below works ok, but since the entries on myBookList are more than one... when i found i match i can't exit the procedure due to the for each iteration (forEach in typescript doesn't accept break or return) and i get always the last entries of the object.
How to solve this?
getValue(data: Row, myKey: string): string {
let retValue: string = "";
data.forEach(function(item) {
item.bookInfo.forEach(function(key, index){
console.log(key, index);
if (key===myKey) {
console.log(key, index);
ret=key.value;
}
});
});
return retValue;
}
You can use while loop. When you meet condition, then we can use return statement to get the desired values:
const getValue = (data, myKey) => {
let i = 0;
while (data.length > i) {
let bookInfoIndex = data[i].bookInfo
.findIndex(f => Object.keys(f).includes(myKey));
if (bookInfoIndex != -1)
return data[i].bookInfo[bookInfoIndex][myKey];
i++;
}
}
An example:
let arr = [{bookInfo: [{title: "The jungle book",isbn: "42398486965239671234",Author: "Rudyard Kipling"}, {title: "20,000 Leagues Under the Sea",isbn: "42234486234239675678",Author: "Jules Verne" },{title: "The Call of the Wild",isbn: "4239848696523967670",Author: "Jack London"}], value: [], id: 0 },
{ bookInfo: [{title: "The jungle book 2",isbn: "327865923874659276",Author: "Rudyard Kipling" }, {title: "20,000 Leagues Under the Sea 2",isbn: "269587649587264675",Author: "Jules Verne"}, {title: "The Call of the Wild",isbn: "2378687827584758765",Author: "Rudyard Kipling"}], value: [], id: 1 }];
const getValue = (data, myKey) => {
let i = 0;
while (data.length > i) {
let bookInfoIndex = data[i].bookInfo.findIndex(f => Object.keys(f).includes(myKey));
if (bookInfoIndex != -1)
return data[i].bookInfo[bookInfoIndex][myKey];
i++;
}
}
console.log(getValue(arr, 'title'));

Angular 2 loop through a list with some delay

How do I loop through an array with some delay with Angular 2 and TypeScript?
I have an array,
students: Array<any> = [
{
name: "Alan"
},
{
name: "Jake"
},
{
name: "Harry"
},
{
name: "Susan"
},
{
name: "Sarah"
},
{
name: "Esther"
}
];
I want to loop through the list and display the names with a 2000ms delay.
<div *ngFor="let student of students">
{{student.name}}
</div>
doesn't work with a delay but is looping all at once.
Just use setTimeout. For example (* not tested):
students: Array<any> = [ ];
populateArrayWithDelay():void{
let people = [
{
name: "Alan"
},
{
name: "Jake"
},
{
name: "Harry"
},
{
name: "Susan"
},
{
name: "Sarah"
},
{
name: "Esther"
}
];
for(let i = 0; i < people.length; i++){
let student = people[i];
setTimeout(() => {
this.students.push(student);
}, 2000*(i+1));
}
}
Plunker example
export class App {
name:string;
students: Array<any> = [
{
name: "Alan"
},
{
name: "Jake"
},
{
name: "Harry"
},
{
name: "Susan"
},
{
name: "Sarah"
},
{
name: "Esther"
}
];
constructor() {
var timer = 0;
this.$students = Observable.from([[], ...this.students])
.mergeMap(x => Observable.timer(timer++ * 1000).map(y => x))
.scan((acc, curr) => {acc.push(curr); return acc;});
}
}

How to remove items in one array if other has it?

How to remove item from array B if array A has it. I want to iterate through by ID.
array A: it has all the items
[{
"Name":"John",
"Id":1
},
{
"Name":"Peter",
"Id":2
},
{
"Name":"Phillip",
"Id":3
},
{
"Name":"Abby",
"Id":4
},
{
"Name":"Don",
"Id":5
}]
array B: has just the selected items
[{
"Name":"John",
"Id":1
},
{
"Name":"Abby",
"Id":4
}]
I want to remove from array A John and Abby by Id, because they are in array b.
for (var i = 0; i < a.length; i++) {
if (b[i].Id == ta[i].Id) {
for (var j = 0; j < b[j]; j++) {
a.splice(i, 1);
}
}
}
this is not working as I thought
You could first get all id's of person objects in b:
let idsInB: number[] = b.map(person => person.Id); // > [1, 4]
This array of id's can be used to filter a, and then assign the result back to a. Let's contain that in a function cleanA:
function cleanA(): void {
let idsInB: number[] = b.map(person => person.Id);
a = a.filter((person) => -1 === idsInB.indexOf(person.Id));
}
All you need to do now is call cleanA whenever the contents of b changes.
Full working example:
interface Person {
Id: number;
Name: string;
}
let a: Person[] = [
{ Id: 1, Name: "John" },
{ Id: 2, Name: "Peter" },
{ Id: 3, Name: "Phillip" },
{ Id: 4, Name: "Abby" },
{ Id: 5, Name: "Don" },
];
let b: Person[] = [
{ Id: 1, Name: "John" },
{ Id: 4, Name: "Abby" },
];
function cleanA(): void {
let idsInB: number[] = b.map(person => person.Id);
a = a.filter((person) => -1 === idsInB.indexOf(person.Id));
}
presentArray(a, 'A before clean');
cleanA();
presentArray(a, 'A after clean');
// -------------------------------------------------------
// Displaying purposes only:
// -------------------------------------------------------
function presentArray(arr, msg) {
document.body.innerHTML += `<br><b>${msg}:</b><br>[<br>`
+ arr.map(person => ` { Id: ${person.Id}, Name: ${person.Name} },<br>`)
.join('')
+ ' ]<br><br>';
}

Resources