Search for a string in javascript and delete it with splice and index nr

javascript array splice
javascript remove object from array
javascript remove element from array by index
remove object from json array javascript
javascript slice
splice in javascript string
remove element from array java
jquery remove item from array by index

I am new to js, I have an array that I need to convert to an object, and then I need to search for a string, and then delete that string.

The first part I can solve of converting a array to an object, I can also search for a string.

The part I can't solve is to retrieve the index nr of the string I searched for and then for example use splice to delete that string in the array.

Here is my code:

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}`)

This is the output:

[ { 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

So in the example above, I would like to find the index nr for the string 'Clean kitchen' and then use splice to delete it. thanks

We can return index from your findTodo and then splice the todoList Array using index in 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("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
    }
  }
}

length + start is less than 0 , it will begin from index 0 . deleteCount Optional: An integer indicating the number of elements in the array to remove  Splitting Strings. JavaScript has a very useful method for splitting a string by a character and creating a new array out of the sections. We will use the split () method to separate the array by a whitespace character, represented by " ".

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

when you are returning the found string instead of returning the string create a object with both found string and the index like below

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

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

so that when you call this function you can use it like this

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

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

Splice, substring, substr, pop, shift & filter can be used. So, how do you delete an element from a JavaScript array? Any element whose index is greater than or equal to the new length will be removed. I find this useful because I often want to retain an original data source, but retrieve subsets based  If endIndex is omitted, slice() extracts to the end of the string. If negative, it is treated as str.length + endIndex. (For example, if endIndex is -3 it is treated as str.length - 3.) Return value. A new string containing the extracted section of the string. Description. slice() extracts the text from one string and returns a new string

You can use Array Filter

const newArray = todos.filter(function (todo) {
     return todo["Task"].toLowerCase() != todoTitle.toLowerCase()
})

Visit each character of the string and slice them in such a way that it removes the newline and carriage return characters. Code snippet:. You have to write you own remove. You can loop over the array, grab the index of the item you want to remove, and use splice to remove it. Alternatively, you can create a new array, loop over the current array, and if the current object doesn't match what you want to remove, put it in a new array.

Add this Code,

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);

JavaScript built-in methods help us a lot while programming, once we understand them correctly. I would like to explain three of them in this article: the slice() , splice() and split() methods. You can find a summary of each method in the end. array.splice(index, number of elements, element, element);. Summary: this tutorial shows you how to use the JavaScript Array’s splice() method to delete existing elements, insert new elements, and replace elements in an array. JavaScript Array type provides a very powerful splice() method that allows you to insert new elements into the middle of an array.

You can use this to find and delete the index

  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;}

and then you can call it as

searchAndDelete("Clean",yourArray)

Voca is a JavaScript library for manipulating strings. The Voca library offers helpful functions to make string manipulations comfortable: change case, trim, pad, slugify, latinise, Returns the first occurrence index of search in subject . v.splice(subjectopt='', start, deleteCountopt=subject.length-start, toAddopt='') → {​string}. Given a string and the task is to remove a character from the given string. Method 1: Using replace () method: The replace method is used to replace a specific character/string with other character/string. It takes two parameters, first is the string to be replaced and the second is the string which is to be replaced with.

Zoek naar een string in JavaScript en verwijder het met splice en index nr toLowerCase() }) return {index:index,foundString:todoList[index]} } toLowerCase() }) return index; // Returning Index of Element } //Call the function to find the string and kitchen"); // Delete Object from Todo console.log("Todo after splicing object[]  The search() method searches a string for a specified value, and returns the position of the match. The search value can be string or a regular expression. This method returns -1 if no match is found. Read more about regular expressions in our RegExp Tutorial and our RegExp Object Reference.

Free online string utilities such as convert to lowercase, convert to uppercase, word count A couple of online string utilities written in JavaScript that you can make use of. Removes empty tokens, which often occurs when two separators are  If endIndex is omitted, slice() extracts to the end of the string. If negative, it is treated as str.length + endIndex. (For example, if endIndex is -3 it is treated as str.length - 3.) Return value. A new string containing the extracted section of the string. Description. slice() extracts the text from one string and returns a new string. Changes to the text in one string do not affect the other string.

Parameter, Description. index, Required. An integer that specifies at what position to add/remove items, Use negative values to specify the position from the end  JavaScript | Array.splice() Method The Array.splice() method is an inbuilt method in JavaScript which is used to modify the contents of an array by removing the existing elements and/or by adding new elements.

Comments
  • you can use Array.splice(index, 1); to delete an element at that index
  • Thanks, I got stuck on this for a while :)
  • I was wondering, is it possible to display the object with all the tasks and their status minus the deleted array, instead of just the array list?
  • @user2371684 i have added a function called deleteFromObject it will delete the value from object . Run the Code Snippet