Найдите строку в javascript и удалите ее с помощью splice и index nr

1

Я новичок в js, у меня есть массив, который мне нужно преобразовать в объект, а затем мне нужно найти строку, а затем удалить эту строку.

Первая часть, которую я могу решить из преобразования массива в объект, я также могу найти строку.

Часть, которую я не могу решить, - это получить индекс nr строки, которую я искал, а затем, например, использовать splice для удаления этой строки в массиве.

Вот мой код:

let todoList = ['Order dog food', 'Clean kitchen', 'Buy food', 'Do homework', 'Exercise']

function strings_to_object(array) {

    // Initialize new empty array
    let objects = [];


    // Loop through the array
    for (let i = 0; i < array.length; i++) {

        // Create the object in the format you want
        let obj = {"Task" : array[i]};

        // Add it to the array
        objects.push(obj);
    }

    // Return the new array
    return objects;
}

//Add additional properties
let Todo = strings_to_object(todoList)
Todo[0].status = 'done'
Todo[1].status = 'done'
Todo[2].status = 'standby'
Todo[3].status = 'done'
Todo[4].status = 'standby'

console.log(Todo)

//function to find a string in the array
const findTodo = function (todos, todoTitle) {
    const index = todos.findIndex(function (todo, index) {
        return todo.toLowerCase() === todoTitle.toLowerCase()
    })
    return todoList[index]
}

//Call the function to find the string and provide the string
const todo = findTodo(todoList, 'CLean kitchen')

console.log('You searched for: ${todo}')

Это результат:

[ { Task: 'Order dog food', status: 'done' },
  { Task: 'Clean kitchen', status: 'done' },
  { Task: 'Buy food', status: 'standby' },
  { Task: 'Do homework', status: 'done' },
  { Task: 'Exercise', status: 'standby' } ]
You searched for: Clean kitchen

Поэтому в приведенном выше примере я хотел бы найти индекс nr для строки "Чистая кухня", а затем использовать сплайс, чтобы удалить его. Спасибо

  • 1
    Вы можете использовать Array.splice(index, 1); удалить элемент по этому индексу
Теги:

5 ответов

1
Лучший ответ

Мы можем вернуть индекс из вашего findTodo, а затем объединить массив todoList с использованием индекса в сращивании

let todoList = ['Order dog food', 'Clean kitchen', 'Buy food', 'Do homework', 'Exercise']

function strings_to_object(array) {

    // Initialize new empty array
    let objects = [];


    // Loop through the array
    for (let i = 0; i < array.length; i++) {

        // Create the object in the format you want
        let obj = {"Task" : array[i]};

        // Add it to the array
        objects.push(obj);
    }

    // Return the new array
    return objects;
}

//Add additional properties
let Todo = strings_to_object(todoList)
Todo[0].status = 'done'
Todo[1].status = 'done'
Todo[2].status = 'standby'
Todo[3].status = 'done'
Todo[4].status = 'standby'
console.log("Orginal Todo");
console.log(Todo)

//function to find a string in the array
const findTodo = function (todos, todoTitle) {
    const index = todos.findIndex(function (todo, index) {
        return todo.toLowerCase() === todoTitle.toLowerCase()
    })
    return index;  // Returning Index of Element
}

//Call the function to find the string and provide the string
const todoIndex = findTodo(todoList, 'CLean kitchen')   // Getting Index

//console.log('You searched for: CLean Kitchen and found at index ${todoIndex}')
todoList.splice(todoIndex,1);   // Splicing array using index
console.log("todoList after splicing array");
console.log(todoList);
deleteFromObject("CLean kitchen");    // Delete Object from Todo
console.log("Todo after splicing object[] ");
console.log(Todo);


function deleteFromObject(todoTitle){
  for(let i=0;i<Todo.length;i++){
    if(Todo[i].Task.toLowerCase() == todoTitle.toLowerCase()){
        Todo.splice(i,1);   // Delete Object
    }
  }
}

Это то что ты хочешь

  • 0
    Спасибо, я немного застрял на этом :)
  • 0
    Мне было интересно, можно ли отобразить объект со всеми задачами и их состоянием минус удаленный массив, а не только список массивов?
Показать ещё 2 комментария
1

Вы можете использовать Array Filter

const newArray = todos.filter(function (todo) {
     return todo["Task"].toLowerCase() != todoTitle.toLowerCase()
})
1
const findTodo = function (todos, todoTitle) {
    const index = todos.findIndex(function (todo, index) {
        return todo.toLowerCase() === todoTitle.toLowerCase()
    })
    return todoList[index]
}

когда вы возвращаете найденную строку вместо того, чтобы возвращать строку, создайте объект с найденной строкой и индексом, как показано ниже

const findTodo = function (todos, todoTitle) {
        const index = todos.findIndex(function (todo, index) {
            return todo.toLowerCase() === todoTitle.toLowerCase()
        })

        return {index:index,foundString:todoList[index]}
    }

так что, когда вы вызываете эту функцию, вы можете использовать ее так

const todo = findTodo(todoList, 'CLean kitchen')

console.log('You searched for: ${todo.foundString} which is at ${todo.index}')
1

Добавьте этот код,

function searchStringInArray (str, strArray) {
        for (var j=0; j<strArray.length; j++) {
            if (strArray[j].Task.match(str)) return j;
        }
        return -1;
    }
var count = searchStringInArray("Clean kitchen", obj);
obj.splice(count, 1);
1

Вы можете использовать это, чтобы найти и удалить индекс

  function searchAndDelete(nameKey, myArray){
   for (var i=0; i < myArray.length; i++) {
    if (myArray[i].Task.includes(nameKey)) {
         console.log(i)
         myArray.splice(i,1)

    }
}
return myArray;}

и тогда вы можете назвать это как

searchAndDelete("Clean",yourArray)

Ещё вопросы

Сообщество Overcoder
Наверх
Меню