user11996757
user11996757

Reputation: 53

Filtering using lodash

I'm currently trying to perform a filter on a list of tests that are of a type ITests. I am using lodash to perform the filtering because someone recommended it to perform this task. What my goal is once I select a test, the test will filter and show it's respective questions. The current filter I have now, I know does not work, I've tried many different variations but can't seem to get the right filter. Any help is greatly appreciated. I hope my questions is concise and makes sense with the provided snippets as well.

Below are snippets of my code:

This is code in my listGroup where I try to filter the questions based on the selectedTests. The common entry I try to look for its moduleName as both test and questions share.

This is inside my ListGroup.tsx the filtering is done here.

import * as React from "react";
import {
  UpdateSelectedTestType,
  UpdateSelectedTest
} from "../actions/TestActions";
import { ITestState } from "../models/ITestState";
import * as _ from "lodash";
interface IProps {
  onUpdatetoggleTestState: typeof UpdateSelectedTestType;
  toggleTestState: ITestState;
  onUpdateSelectedTest: typeof UpdateSelectedTest;
}
export class ListGroup extends React.Component<IProps> {
  public render() {
    let question = null
    if(this.props.toggleTesttate.selectedTest !=  undefined)
      var selectedtest = this.props.toggleTestState.selectedTest.moduleName
      questions = this.props.toggleTestState.questions
      var filterquestions = _.filter(questions, function(o){
        return _.isMatch(o, selectedtest )
      })
     console.log(filterquestion)
    return (
    );
  }
}

This is my toggleButtonReducer.ts

const initialState: ITestState = {
  testype: TestType.test1,
  tests: dbTest,
  questions: dbQuestions,
  selectedTest: undefined
  //selectedQuestion: undefined
};

The tests and questions share a common entry called moduleName so therefore I will be using this field to access the filtered questions based on the selected test.

This is my testActions.ts

export interface ITest {
  name: string;
  moduleName: string;
  testType: TestType


 export interface ITest {
      name: string;
      moduleName: string;

Upvotes: 0

Views: 303

Answers (1)

Drew Reese
Drew Reese

Reputation: 202706

Javascript has built-in array filtering now that may have an easier API. It takes a callback that has the element, index, and original array passed to it and you can take as many of them as needed.

[edit] Added check if selectedTest is an array of module names

let selectedtest = this.props.toggleTestState.selectedTest.moduleName
let questions = this.props.toggleTestState.questions
let filteredQuestions = questions.filter(
  question => {
    if (Array.isArray(selectedTest) {
      return selectedTest.includes(question.moduleName);
    } else {
      return question.moduleName === selectedTest;
    }
  }
);

Upvotes: 1

Related Questions